enumerate, zip, range
- Iterate with
enumerate()for indexed loops - Loop over multiple sequences in parallel with
zip() - Reverse iteration with
reversed() - Sort iterables by custom keys with
sorted(..., key=...)
enumerate and zip are the mark of Pythonic code; reviewers flag for i in range(len(x)) on sight. dict.items() shows up in every config loader, template renderer, and ORM serializer in the ecosystem.
- Writing
for i in range(len(lst)): lst[i]instead ofenumerate(lst). It works but reads as non-Pythonic in code review. - Assuming
ziperrors on unequal lengths. It silently truncates; usezip(a, b, strict=True)on Python 3.10+ to catch mismatches. - Calling
.items()and unpacking wrong:for k, v in d.items()is correct;for k in d.items()gives you tuples.
Three iteration patterns you'll reach for every day.
enumerate(seq, start=0)
Gives you (index, value) tuples. Stop writing for i in range(len(x)).
zip(a, b)
Walks multiple sequences in parallel. Stops at the shortest one.
range(start, stop, step)
Lazy sequence of integers. Convert with list(range(...)) if you need a list.
Try it
- Use
zipto build a dict fromnamesandyears. - Print every other item of a list using
enumerate+ a check on the index.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Given
fruits = ["apple", "banana", "cherry"], useenumerate(starting at1) to print each fruit as"1. apple","2. banana","3. cherry"— one per line. - Exercise 2
Use
zipto pairnames = ["Ada", "Grace", "Linus"]withyears = [1815, 1906, 1969], build a dict name→year, and print it. Expected:{'Ada': 1815, 'Grace': 1906, 'Linus': 1969}. - Exercise 3
Using
rangeand a step, print every odd number from 1 to 15 inclusive on a single line separated by spaces. Expected exactly:1 3 5 7 9 11 13 15.