Tuples and Sets¶
By the end of this lesson you'll be able to:
- Create and unpack tuples, and explain when to use them instead of lists
- Return multiple values from a function using a tuple
- Create a set and use
union(),intersection(), anddifference()for set math - Test membership in a set and add or remove items
Python gives you four main collection types. You've mastered lists. Now let's meet two more: tuples and sets.
Welcome to Chapter 20!
Tuples are like lists that are locked in place — perfect for things that should never change.
Sets are like bags where duplicates are forbidden and order doesn't matter.
Let's explore both! Let's code it together!
The Tuple Type¶
A tuple is an ordered, immutable (unchangeable) collection of items. You create one using parentheses with items separated by commas.
1 2 3 | |
Tuples look and act a lot like lists, but they cannot be changed after creation. You cannot add, remove, or reassign items in a tuple.
When to Use a Tuple Instead of a List¶
Use a tuple when the data is fixed and shouldn't change:
| Use case | Example |
|---|---|
| Coordinates | (x, y) or (x, y, z) |
| RGB color values | (255, 0, 128) |
| Days of the week | ("Mon", "Tue", ...) |
| Function return values | return (lat, lng) |
Use a list when you need to add, remove, or change items over time.
Single-Element Tuple Syntax¶
A tuple with one item needs a trailing comma — otherwise Python just sees parentheses around a value:
1 2 | |
The trailing comma is the signal to Python that you mean a tuple.
Tuple Unpacking¶
Tuple unpacking assigns each item in a tuple to a separate variable in one step. This makes code clean and expressive.
1 2 3 4 | |
What Do You Think Will Happen?
The code below unpacks a tuple with three items.
What values do you think a, b, and c will have?
Make your guess — then run it!
Tuples as Return Values¶
Functions can return multiple values by packing them into a tuple. The caller unpacks the result:
1 2 3 4 5 | |
The Set Type¶
A set is an unordered collection of unique items. Two key properties: 1. No duplicates — adding the same item twice has no effect 2. No guaranteed order — items may print in any order
Create a set with curly braces {} or the set() constructor:
1 2 | |
Sets are most useful for: - Removing duplicates from a list - Fast membership testing (faster than lists for large collections) - Mathematical set operations
Set Methods: add(), remove(), discard()¶
s.add(x)— addsxto the set (no effect if already present)s.remove(x)— removesx; raisesKeyErrorif not founds.discard(x)— removesxif present; silently does nothing if not found
Use discard() when you're not sure whether the item exists.
Set Operations: Union, Intersection, Difference¶
Before we try them, here's what each operation means:
- Union (
|) — all items from both sets (no duplicates) - Intersection (
&) — only items that appear in both sets - Difference (
-) — items in the first set but not the second
1 2 3 4 5 6 7 | |
See It: Set Operations on a Venn Diagram¶
What Do You Think Will Happen?
In the diagram below, set A has dog, cat, fish, and bird; set B has cat,
bird, snake, and hamster. Before you click any operation button, predict:
which animals will A & B give you? Then click and see which region
lights up!
Explore the Set Operations Venn MicroSim
Click all four operations and watch which region glows for each. Then edit the sets — type your own items, and try entering the same animal twice in one set to see the set collapse the duplicate. Notice that A & B with no shared items gives set(), Python's way of writing an empty set.
Frozensets¶
A frozenset is an immutable version of a set — you cannot add or remove items after creation. This makes it usable as a dictionary key or stored inside another set (regular sets can't do this).
1 2 3 | |
Learning Check¶
Your Turn — Find Shared Interests
Two friends listed their favorite animals. Write code to find which animals they both like.
Use the set intersection operator & to find the shared items!
Experiments¶
Try these changes. Predict what will happen first, then run it to check!
-
Create a tuple of seven colors of the rainbow. Unpack the first three into
r,o,y. You'll know it worked when three color names are printed without errors. -
Write a function
circle_stats(radius)that returns the area and circumference as a tuple. Usemath.pi. Unpack and print both values. You'll know it worked when radius 5 gives area ≈ 78.54 and circumference ≈ 31.42. -
Convert the list
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3]to a set and back to a sorted list. You'll know it worked when you see[1, 2, 3, 4, 5, 6, 9]— duplicates removed. -
Try adding an item to a frozen set. Read the error message carefully. You'll know it worked when you see
AttributeError: 'frozenset' object has no attribute 'add'. -
Use the
|union operator to merge two sets of numbers and print the sorted result. You'll know it worked when you see a combined list with no duplicates.
Collection Expert!
You've mastered tuples for fixed data and sets for unique collections!
Now you have four collection tools: list, tuple, set, and (coming next) dictionary.
Each has its place — knowing when to use which one is a real programming skill!