Kodokon kodokon.com

Advanced structures: tuples, sets and collections

Pick the structure that fits each need: immutable tuples, sets for O(1) membership tests, Counter and defaultdict for recurring patterns.

9 min · 3 questions

Open this lesson in Kodokon

Choosing the right data structure settles both readability and performance in one move. The tuple is an immutable sequence: ideal for a fixed-size heterogeneous record (coordinates, a key-value pair). Immutable implies hashable (if its contents are): a tuple can therefore serve as a dictionary key or a set element, which a list cannot. Unpacking makes code expressive - and a function that "returns several values" actually returns a tuple.

PYTHON
point = (48.85, 2.35)
lat, lon = point

def min_max(values):
    return min(values), max(values)

low, high = min_max([3, 1, 4, 1, 5])
print(low, high)

distances = {("paris", "lyon"): 465}
print(distances[("paris", "lyon")])
Unpacking, multiple return and a tuple as a dict key

The set guarantees uniqueness and offers a membership test in O(1) on average, where a list is O(n). In a loop that checks x in collection thousands of times, the difference shows up immediately. Set operators (& intersection, - difference, | union) are a real upgrade over nested loops: comparing two lists of identifiers - who disappeared, who is new - fits in two lines.

PYTHON
active = {"ada", "linus", "guido"}
banned = {"linus", "mallory"}

print(active & banned)
print(active - banned)
print(active | banned)

emails = ["a@x.io", "b@x.io", "a@x.io"]
unique = set(emails)
print(len(unique))
Set operations and deduplication

The collections module covers two everyday needs. Counter counts the occurrences in an iterable and exposes most_common(n) - no more hand-written counting dictionaries. defaultdict(factory) builds the missing value on the fly: defaultdict(list) is the canonical tool for grouping elements by key without testing the key's existence on every pass of the loop.

PYTHON
from collections import Counter, defaultdict

words = ["go", "py", "go", "rs", "go"]
counts = Counter(words)
print(counts.most_common(2))

groups = defaultdict(list)
pairs = [("fr", "Ada"), ("us", "Lin"), ("fr", "Zoe")]
for country, name in pairs:
    groups[country].append(name)
print(dict(groups))
Counter to count, defaultdict to group

Knowledge check

Make sure you remember the key points of this lesson.

  1. Why can a tuple serve as a dictionary key, unlike a list?
    • It is faster to create
    • It is immutable, therefore hashable
    • It can only contain numbers
    • Dictionaries convert lists into tuples
  2. You test x in collection thousands of times over 100,000 elements. Which structure should you choose?
    • A list, scanned sequentially
    • A set, membership in O(1) on average
    • A tuple, more compact than a list
  3. With groups = defaultdict(list), what does reading a missing key do?
    • It raises KeyError
    • It returns an empty list and inserts the key
    • It returns None without modifying the dictionary