Tuples and sets · 5 / 16 Theory

Unpacking, named tuples and frozenset

Tuples shine when combined with unpacking: spreading the elements of a sequence into variables in a single line.

from collections import namedtuple

a, b = 1, 2
a, b = b, a                              # swap without a helper variable
print(a, b)                              # 2 1

first, *rest = [10, 20, 30, 40]
print(first, rest)                    # 10 [20, 30, 40]
*start, last = (1, 2, 3)
print(start, last)                    # [1, 2] 3

for name, (x, y) in [("A", (1, 2)), ("B", (3, 4))]:   # nested unpacking
    print(name, x + y)                 # A 3  /  B 7

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p, p.x, p[1])                      # Point(x=3, y=4) 3 4
print(p._replace(x=9))                   # Point(x=9, y=4)   (creates another: tuples do not change)
print(p._asdict())                       # {'x': 3, 'y': 4}
x, y = p                                 # it is still a tuple: it can be unpacked
print(x + y, p == (3, 4))                # 7 True

groups = {}
for word in ["abba", "ab", "baab"]:
    groups.setdefault(frozenset(word), []).append(word)   # frozenset: valid key
print(list(groups.values()))             # [['abba', 'ab', 'baab']]
  • a, b = b, a swaps two values without a helper variable.
  • first, *rest = sequence gathers the leftovers in a list; the * can be at the beginning, in the middle or at the end, but only once.
  • namedtuple creates a tuple with named fields: more readable than p[0], just as light and immutable. To change a field you use _replace, which creates another one.
  • Sets are mutable and cannot be dictionary keys; frozenset (immutable) can, and they let you group or count by “set of elements” regardless of order.

You practice it in Points with named tuples, Words with the same letters and Unpacking with a star.