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

2 exercises

2 quizzes

0/4 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.

Walkthrough

zip pairs items by position

daysMonTueWed012itemps211901i
Step 1 of 3
pair = ('Mon', 21)

zip takes the first item of each list and hands them out together as a tuple.

paired now
already paired
dropped

zip(days, temps)

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).
Exercise

Ranked scores

Write a function leaderboard(names, scores) that returns one string per player, numbered from 1 in the order given: "1. Ana: 91", "2. Ben: 85", and so on. Use zip to pair each name with its score and enumerate to number them.