enumerate and zip

The position of an element and looping in parallel.

When a loop needs both the element and its number, beginners write for i in range(len(items)) and fetch items[i]. It works, but it is not how things are done in Python. enumerate gives "number, element" pairs:

tasks = ["read", "write", "test"]
for number, task in enumerate(tasks, start=1):
    print(number, task)

The start parameter sets the first number. By default counting starts at zero.

zip goes through several sequences at once and gives tuples of the elements at the same position:

names = ["Ann", "Bob"]
scores = [90, 75]
for name, score in zip(names, scores):
    print(name, score)

zip stops at the shortest sequence, and the extra elements are silently dropped. If the lengths must match, in Python 3.10 and later you can pass strict=True, and different lengths will raise an error.

The pair dict(zip(keys, values)) builds a dictionary from two lists, a common trick when parsing tables. enumerate and zip do not return lists but lazy iterators. To see the whole result, wrap it in list(...). In a for loop there is no need to.

Practice

  1. A short zip

    What does the program print?

    print(list(zip("ab", [1, 2, 3])))
    
  2. The position of an element

    How is a list usually looped over in Python when you need both the number and the element?

    • for i, item in enumerate(items)
    • for i in range(len(items)): item = items[i]
    • for item in items: i = items.index(item)
    • for i, item in items
  3. A numbered list

    Write a function numbered(items) that returns a list of strings of the form "1. tea", with numbering starting from one.