enumerate, zip, reversed and sorted
Add a fourth color and a fourth score and run again. Then remove one score and see how zip quietly drops the extra name.
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.
Print the list ["milk", "eggs", "bread"] as 1. milk, 2. eggs, 3. bread using enumerate.
Given items = ["pen", "book", "bag"] and prices = [10, 45, 120], print pen costs 10 and so on using zip.
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
Why is enumerate preferred to range(len(items))?
What happens when you zip lists of different lengths, and how do you make it safe?
What is the difference between sorted(x) and x.sort()?
What does for i, (a, b) in enumerate(zip(xs, ys)) do?
Expected output
0 red
1 green
2 blue
1. red
2. green
3. blue
Asha scored 90
Ben scored 72
Chen scored 85
Backwards: blue
Backwards: green
Backwards: red
[1, 2, 3]
['Cherry', 'apple', 'banana']
['Chen', 'Ben', 'Asha']
['red', 'green', 'blue']