Tuples & Sets
Tuples & Sets
Python provides two more important built-in collection types: tuples (ordered, immutable) and sets (unordered, mutable, no duplicates).
Tuples
A tuple is like a list that cannot be changed after creation. Use parentheses (or just commas) to define one:
point = (3, 7)
colors = ("red", "green", "blue")
single = (42,) # trailing comma required for single-element tuple
nothing = () # empty tupleWhy use tuples?
- Hashable (can be dict keys or set members)
- Slightly faster than lists
- Signal to readers that the data should not change
- Used as function return values to group multiple items
Tuple Unpacking
Unpacking assigns each element of a tuple to a variable in one statement:
x, y = (10, 20)
first, *rest = (1, 2, 3, 4, 5) # *rest captures remaining items
a, b, c = "ABC" # works on any iterableNamed Tuples
collections.namedtuple adds field names without the overhead of a full class:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 7)
print(p.x, p.y) # 3 7
print(p[0]) # 3 — still index-accessibleSets
A set is an unordered collection of unique items. It is ideal for membership tests and eliminating duplicates:
s = {1, 2, 3, 3, 2} # {1, 2, 3}
empty_set = set() # NOT {} — that creates a dict!Common Set Methods
| Method / Operator | Meaning |
|---|---|
s.add(x) | Add single element |
s.remove(x) | Remove x; raises KeyError if absent |
s.discard(x) | Remove x; no error if absent |
s.pop() | Remove & return an arbitrary element |
| `A | BorA.union(B)` |
A & B or A.intersection(B) | Elements in both |
A - B or A.difference(B) | Elements in A but not B |
A ^ B or A.symmetric_difference(B) | Elements in A or B but not both |
A <= B or A.issubset(B) | True if A is a subset of B |
Frozenset
A frozenset is an immutable set — it can be used as a dictionary key or placed inside another set:
fs = frozenset([1, 2, 3])
d = {fs: "immutable set as key"} # valid!When to Use Each
| Use case | Best type |
|---|---|
| Ordered, changeable sequence | list |
| Ordered, unchangeable record | tuple |
| Unique membership / set math | set |
| Immutable set (dict key) | frozenset |
Code Examples
# Basic tuple
coordinates = (10.5, 20.3, 5.0)
print("Coordinates:", coordinates)
print("X:", coordinates[0])
# Tuple unpacking
x, y, z = coordinates
print(f"x={x}, y={y}, z={z}")
# Extended unpacking
first, *middle, last = (1, 2, 3, 4, 5)
print("first:", first)
print("middle:", middle)
print("last:", last)
# Swap variables elegantly
a, b = 10, 20
a, b = b, a
print(f"After swap: a={a}, b={b}")
# Single-element tuple
singleton = (42,)
print("Type:", type(singleton))Tuple unpacking is one of Python's most elegant features. The starred expression (*middle) collects all 'remaining' elements into a list. Variable swapping without a temp variable is made possible by implicit tuple packing/unpacking.
from collections import namedtuple
# Define a named tuple type
Employee = namedtuple("Employee", ["name", "department", "salary"])
# Create instances
emp1 = Employee("Alice", "Engineering", 95000)
emp2 = Employee("Bob", "Marketing", 72000)
# Access by name or index
print(emp1.name, emp1.department)
print(emp2[2]) # salary by index
# Named tuples are still immutable
try:
emp1.salary = 100000
except AttributeError as e:
print("Error:", e)
# Convert to dict
print(emp1._asdict())namedtuple creates a lightweight class with named fields. Instances are immutable like regular tuples but far more readable. _asdict() converts to an OrderedDict for easy serialization.
python_devs = {"Alice", "Bob", "Carol", "Dave"}
js_devs = {"Bob", "Dave", "Eve", "Frank"}
# Union — all developers
all_devs = python_devs | js_devs
print("All devs:", sorted(all_devs))
# Intersection — know both languages
both = python_devs & js_devs
print("Know both:", sorted(both))
# Difference — Python only
python_only = python_devs - js_devs
print("Python only:", sorted(python_only))
# Symmetric difference — know exactly one
one_lang = python_devs ^ js_devs
print("One language:", sorted(one_lang))
# Fast membership test
print("Alice in Python devs:", "Alice" in python_devs)
# Remove duplicates from a list
with_dupes = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(with_dupes))
print("Unique:", sorted(unique))Set operations mirror mathematical set theory. Membership testing in a set is O(1) (constant time) versus O(n) for a list, making sets ideal for lookup-heavy code. Converting a list to a set is the quickest way to deduplicate.
Quick Quiz
1. How do you create an empty set in Python?
2. What does the & operator do when applied to two sets?
3. Which of the following is a valid single-element tuple?
4. What makes frozenset different from set?
Was this lesson helpful?