Python for Polyglots
Lesson 4 · Idioms

Loops, zip & unpacking

Python's for loop is always a for-each. You rarely touch indexes directly.

  • for item in items: loops over the items themselves.
  • for i, item in enumerate(items): gives you the index too.
  • for a, b in zip(xs, ys): walks two lists in step, pairing them like a zipper. It stops at the shortest list.
  • for k, v in d.items(): loops over a dict's keys and values.

Unpacking

The left side of an assignment can be a pattern. A *name catches "the rest" as a list, and it can go anywhere in the pattern, not only at the end.

first, *rest = [1, 2, 3, 4]   # 1, [2, 3, 4]
*init, last  = [1, 2, 3, 4]   # [1, 2, 3], 4
a, *mid, z   = [1, 2, 3, 4]   # 1, [2, 3], 4
a, b = b, a                   # swap, no temp variable

The same stars spread values in a call: f(*args) spreads a list into positional arguments, and f(**opts) spreads a dict into keyword arguments. Like JS ....

Numbered list
fruits = ["apple", "kiwi", "plum"]
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")
Experiment
names = ["ana", "bo", "cy"]
scores = [90, 85, 70]

for i, name in enumerate(names):
    print(i, name)

for name, score in zip(names, scores):
    print(f"{name:>4} scored {score}")

print(dict(zip(names, scores)))

first, *rest = names
print(first, rest)

def total(*nums):
    return sum(nums)
print(total(*scores))
Quiz: What does this print?
first, *rest = "hi"
print(first, rest)
Quiz: What does this print?
print(list(zip([1, 2, 3], "ab")))
Exercise 4: Index of the max

Return the index of the largest number (the first one if there's a tie). Return None for an empty list.

index_of_max([3, 9, 2, 9]) → 1

Exercise 5: Pair two lists

Combine two lists into a dict {name: score}. If one list is longer, ignore the extras.

pair_up(["ana", "bo"], [90, 85]) → {"ana": 90, "bo": 85}

Exercise 6: First and rest

Return a tuple (first_item, list_of_the_rest). For an empty list, return (None, []).

first_and_rest([1, 2, 3]) → (1, [2, 3])

Exercise 7: Swap the ends

Return a new list with the first and last items swapped. Don't modify the original.

swap_ends([1, 2, 3, 4]) → [4, 2, 3, 1]