enumerate() and zip()

Comprehensions & Iteration, lesson 3 of 5

⚡ Comprehensions & Iteration, lesson 3 of 5

enumerate() and zip()

Loop with an index, or walk through several lists side by side.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Need the position and the item? Instead of range(len(items)), use enumerate. It hands you (index, item) pairs. Pass start=1 to count from 1.

Example

Numbered to-do list

Remove start=1 and see where the numbering begins.

Example

Find the spikes

The index tells you where each spike happened.

Quiz

What does this print?

zip walks through several sequences side by side, giving you a tuple with one item from each. dict(zip(keys, values)) is a quick way to pair two lists into a dictionary.

Example

Zip names and scores

Add a third list, ages, and zip all three.

Example

Shortest wins

Where did Wednesday go? Add strict=True inside zip(...) to get an error instead.

Example

Day-to-day changes

Zipping a list with itself shifted by one gives neighbouring pairs. :+ always shows the sign.

Quiz

What does this print?

Exercise

Invoice builder

The three lists line up by position.

  1. totals: a dict mapping each item to qty * price (use zip).
  2. grand_total: the sum of all the totals.
  3. numbered: ["1. pen", "2. pad", "3. ink"] (use enumerate).