Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.6 — Looping Like a Pythonista: enumerate and zip
Python · Example 2 of 2 Python 3.10+

zip stops quietly, strict=True fails loudly

This program ends with an error on purpose. Read the last line, then add a third score (for example 85) so both lists have three items and the error disappears.

enumerate gives you the position and the item together, zip walks several sequences in step, and reversed and sorted change the order. They replace the beginner pattern for i in range(len(x)).

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print the list ["milk", "eggs", "bread"] as 1. milk, 2. eggs, 3. bread using enumerate.

02

Given items = ["pen", "book", "bag"] and prices = [10, 45, 120], print pen costs 10 and so on using zip.

03

Print the numbers 1, 2, 3 in reverse order using reversed, one per line, and then print the sorted version of [5, 2, 9, 1] followed by the original list.

Explain it without notes

01

Why is enumerate preferred to range(len(items))?

02

What happens when you zip lists of different lengths, and how do you make it safe?

03

What is the difference between sorted(x) and x.sort()?

04

What does for i, (a, b) in enumerate(zip(xs, ys)) do?

zip stops quietly, strict=True fails loudly Python 3.10+
Sign in to run this example in your browser.

Expected output

[('Asha', 90), ('Ben', 72)]
Asha 90
Ben 72
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    for name, score in zip(names, scores, strict=True):
                       ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: zip() argument 2 is shorter than argument 1