Data Structures in Python
Tuples & Sets
Immutable tuples for fixed records and packing/unpacking, and sets for uniqueness and fast membership — with union, intersection and difference.
Tuples
A tuple is an ordered, immutable sequence. Use it for fixed groups of values: coordinates, RGB colours, a database row, multiple return values.
point = (3, 4)
rgb = 255, 128, 0 # brackets are optional
single = (42,) # a one-item tuple needs a trailing comma
print(point[0], rgb, type(single), len(rgb))
x, y = point # unpacking
print(f"x={x}, y={y}")
def min_max(values):
return min(values), max(values) # returns a tuple
lo, hi = min_max([7, 2, 9, 4])
print(lo, hi)
# point[0] = 5 # TypeError: tuples are immutable3 (255, 128, 0) <class 'tuple'> 3 x=3, y=4 2 9
| List | Tuple |
|---|---|
[1, 2, 3] |
(1, 2, 3) |
| mutable | immutable |
| many methods | only count and index |
| variable collections | fixed records |
| cannot be a dict key | can be a dict key (if its items are hashable) |
| slightly more memory | slightly less memory |
distances = {("Delhi", "Agra"): 233, ("Mumbai", "Pune"): 149} # tuple keys
print(distances[("Mumbai", "Pune")])
from collections import namedtuple
Student = namedtuple("Student", ["name", "roll", "cgpa"])
s = Student("Asha", 101, 9.1)
print(s.name, s.cgpa, s)149 Asha 9.1 Student(name='Asha', roll=101, cgpa=9.1)
Sets
A set is an unordered collection of unique, hashable items. It is a hash table underneath, so membership tests are O(1) on average.
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
unique = set(nums)
print(unique, len(unique))
unique.add(7)
unique.discard(100) # no error if missing (remove() would raise KeyError)
print(4 in unique, 8 in unique)
print(sorted(unique))
empty = set() # {} would be an empty DICT{1, 2, 3, 4, 5, 6, 9} 7
True False
[1, 2, 3, 4, 5, 6, 7, 9]Set operations
Sets support the operations from Discrete Mathematics directly:
| Operation | Operator | Method |
|---|---|---|
| Union A ∪ B | a | b |
a.union(b) |
| Intersection A ∩ B | a & b |
a.intersection(b) |
| Difference A − B | a - b |
a.difference(b) |
| Symmetric difference A ⊕ B | a ^ b |
a.symmetric_difference(b) |
| Subset A ⊆ B | a <= b |
a.issubset(b) |
python_club = {"Asha", "Ravi", "Meera", "Kiran"}
dsa_club = {"Ravi", "Kiran", "Zoya"}
print("both clubs: ", sorted(python_club & dsa_club))
print("either club: ", sorted(python_club | dsa_club))
print("only python: ", sorted(python_club - dsa_club))
print("exactly one: ", sorted(python_club ^ dsa_club))
print({"Ravi", "Kiran"} <= dsa_club)both clubs: ['Kiran', 'Ravi'] either club: ['Asha', 'Kiran', 'Meera', 'Ravi', 'Zoya'] only python: ['Asha', 'Meera'] exactly one: ['Asha', 'Meera', 'Zoya'] True
A frozenset is an immutable set, usable as a dictionary key or as an element of another set.
Test yourself
4 questions · pick an answer to check it instantly
- 1
How do you write a tuple containing only the number 5?
(5)is just the number 5 in brackets; the comma makes it a tuple. - 2
What is
len({1, 2, 2, 3, 3, 3})?Sets keep only unique elements. - 3
For
a = {1, 2, 3}andb = {2, 3, 4}, what isa - b?Difference keeps the elements ofathat are not inb. - 4
Which can be used as a dictionary key?
Keys must be hashable (immutable); tuples of immutable items are.