Learn Python in 30 Days — Day 11: Tuples & Sets

Learn Python in 30 Days — Day 11: Tuples & Sets

Welcome to Day 11 of the Learn Python in 30 Days series!

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

You’ve already worked with lists which are flexible, changeable collections that hold multiple values.
Today we’ll learn two other collection types that expand your Python toolkit:

  • Tuples → fixed collections that can’t change.

  • Sets → unordered collections that remove duplicates automatically.

These are subtle but powerful tools that will make your code more efficient, safe, and expressive.

Step 1 – Tuples: Data You Don’t Want to Change

Tuples look like lists, but they use round brackets () instead of square ones [].
Most importantly they are immutable (unchanging).
Once created, you can’t add, remove, or modify items inside a tuple.

# Tuple example my_tuple = ("apple", "banana", "cherry") print(my_tuple)

Try to change one element:

my_tuple[0] = "orange" # Error! Tuples are immutable

You’ll get a TypeError. This is Python protecting your data, once a tuple is defined, it stays the same forever.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Why Use Tuples?

  1. Safety — When you don’t want data to change by mistake.

  2. Speed — Tuples are slightly faster and more memory-efficient than lists.

  3. Hashability — Because they can’t change, tuples can be used as dictionary keys or set elements where as lists can’t!

For example:

location = (51.5074, -0.1278) # London place_info = {location: "London, UK"}

Lists are mutable → not hashable → not allowed as dictionary keys.
Tuples solve that problem neatly.

Tuple Unpacking

Python lets you “unpack” tuple values into separate variables in a single line, this is one of the cleanest ways to handle multiple values at once.

person = ("Matty", 30, "Engineer") name, age, job = person print(f"Name: {name}, Age: {age}, Job: {job}")

This works because the number of variables on the left matches the number of elements in the tuple.

You can even use it to swap variables without a temporary one:

a, b = 10, 20 a, b = b, a print(a, b) # 20 10

That’s tuple unpacking in action!

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Single-Item Tuples

If you ever need a tuple with just one item, don’t forget the comma:

single = ("hello",) print(type(single)) # <class 'tuple'>

Without the comma, Python would think it’s just a string in parentheses.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

When to Use Tuples

Use a tuple when:

  • You want data that should not change (e.g., coordinates, RGB values, config options).

  • You want to use data as a dictionary key or part of a set.

  • You want lightweight, fast, read-only containers.

Example:

rgb = (255, 128, 0) # Orange print(f"R:{rgb[0]} G:{rgb[1]} B:{rgb[2]}")

Step 2 – Sets: Collections That Keep Things Unique

A set is an unordered collection of unique items.
You make one using curly braces {} or the set() function.

fruits = {"apple", "banana", "apple", "cherry"} print(fruits)

Output:

{'banana', 'cherry', 'apple'}

Notice:

  • Duplicates are gone!

  • The order may not match what you typed as sets are unordered.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Working with Sets

You can add or remove elements:

fruits.add("orange") fruits.remove("banana")

And you can check if something exists inside a set (very fast!):

if "apple" in fruits: print("Apple is in the set.")

Sets are especially good when you need to:

  • Eliminate duplicates

  • Compare large collections quickly

  • Perform mathematical-style operations like union, intersection, and difference

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Set Operations

Set operations allows us to manipulate the data in different ways, such as adding, removing or clearing the set. The following operations can be preformed: -

MethodWhat It Does
add(item)Inserts a single element into the set. If it already exists, nothing changes.
remove(item)Deletes the specified element. Raises an error if it doesn’t exist.
discard(item)Removes the element if present — skips it silently if it’s not there.
pop()Removes and returns a random element (since sets are unordered).
clear()Empties the entire set, leaving it blank.
copy()Creates a shallow duplicate of the set.
union(other_set)Combines two or more sets into one, removing duplicates automatically.
intersection(other_set)Returns elements that exist in both sets.
difference(other_set)Returns elements that exist in the first set but not in the second.
symmetric_difference(other_set)Returns items that appear in either set, but not in both.
issubset(other_set)Checks whether every element in this set exists in another.
issuperset(other_set)Checks whether this set contains every element of another.
isdisjoint(other_set)Returns True if the two sets share no common elements.

These methods also have shortcuts so we don't need to type the whole command. The following table shows the different shortcuts available.

OperatorEquivalent MethodExample
``union()
&intersection()a & b
-difference()a - b
^symmetric_difference()a ^ b
<=issubset()a <= b
>=issuperset()a >= b

Let’s see how these work with an example:

a = {1, 2, 3, 4} b = {3, 4, 5, 6} print("Union:", a | b) print("Intersection:", a & b) print("Difference:", a - b) print("Symmetric Difference:", a ^ b)

Output:

Union: {1, 2, 3, 4, 5, 6} Intersection: {3, 4} Difference: {1, 2} Symmetric Difference: {1, 2, 5, 6}

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Set Comprehensions

Like list comprehensions, sets can be created on the fly:

numbers = [1, 2, 2, 3, 4, 4, 5] squared = {n**2 for n in numbers} print(squared) # {1, 4, 9, 16, 25}

This instantly removes duplicates while transforming data cleanly and efficiently.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Frozen Sets

A frozenset is an immutable version of a set once created, you can’t add or remove items.

They’re useful when you want to use a set as a dictionary key or keep a reference that must never change.

permissions = frozenset(["read", "write"]) print(permissions)

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Real-World Example – Removing Duplicates

Let’s say you scrape a list of emails, but there are duplicates:

emails = ["a@x.com", "b@y.com", "a@x.com", "c@z.com"] unique_emails = set(emails) print(f"Unique emails ({len(unique_emails)}): {unique_emails}")

That’s how data cleanup is done in one simple line.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub herehere and run it yourself.

Mini Project – Student Course Tracker

Combine tuples and sets for a small real-world demo:

available_courses = ("Math", "Science", "History", "Art") my_courses = {"Math", "Art"} print("All courses:", available_courses) print("My courses:", my_courses) remaining = set(available_courses) - my_courses print("Still available:", remaining)

Output:

All courses: ('Math', 'Science', 'History', 'Art') My courses: {'Math', 'Art'} Still available: {'Science', 'History'}

Tuples define the fixed list of available courses.
Sets track what you’re taking and handle the math cleanly.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Summary

TypeMutableOrderedDuplicatesSyntaxTypical Use
List✅ Yes✅ Yes✅ Yes[]General-purpose storage
Tuple❌ No✅ Yes✅ Yes()Fixed data, coordinates, safe storage
Set✅ Yes❌ No❌ No{}Unique data, fast comparisons
Frozen Set❌ No❌ No❌ Nofrozenset()Immutable unique data

Quick Recap

  • Tuples protect data from change and can be unpacked easily.

  • Sets remove duplicates and perform lightning-fast comparisons.

  • Frozen sets are unchangeable sets useful for fixed relationships.

When you combine these with lists and dictionaries, you now have the full set of Python’s core collection types!

Next up — Day 12 – Dictionaries

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

You can see the full series here Learn Python in 30 Days series!

Hope you have enjoyed this post, thanks Matty

Comments

Popular posts from this blog

Math Behind Logic Gates

6502 - Part 2 Reset and Clock Circuit

Building a 6502 NOP Test