Bytebook Compiler

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.

3 min read4 runnable examples4-question quiz

Tuples

A tuple is an ordered, immutable sequence. Use it for fixed groups of values: coordinates, RGB colours, a database row, multiple return values.

Python
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 immutable
Output
3 (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
Python
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)
Output
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.

Python
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
Output
{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
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)
Output
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. 1

    How do you write a tuple containing only the number 5?

  2. 2

    What is len({1, 2, 2, 3, 3, 3})?

  3. 3

    For a = {1, 2, 3} and b = {2, 3, 4}, what is a - b?

  4. 4

    Which can be used as a dictionary key?