Hone

Lessons · Python · zip (walk two lists)

Walking two lists together

zip(a, b) pairs items by position, so one loop can use both.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Names and scores, timestamps and readings, headers and row cells: parallel lists are everywhere, and zip is how you walk them without index arithmetic.

How to think about it

Am I indexing two lists with the same i? If you are writing for i in range(len(a)) just to read a[i] and b[i], you want zip. Name the pair in the loop: for name, score in zip(names, scores).

Worked example

names = ["ada", "bo"]; scores = [90, 72]
Parallel.
for name, score in zip(names, scores):
Pairs: (ada, 90), (bo, 72).
    print(f"{name}: {score}")
ada: 90, then bo: 72.
print(dict(zip(names, scores)))
{"ada": 90, "bo": 72}: pairs make a dict directly.

Your turn

Total each pair of numbers position by position.

sums = [x + y for x, y in (a, b)]

The trap

zip stops at the shorter list, silently. If lengths should match, check them, or use zip(strict=True).

Practise zip (walk two lists) on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.