← Back to Python, page 2

python-0024 · Easy fresher

How do enumerate and zip make loops cleaner, and what does zip do with unequal lengths?

enumerate(iterable, start) yields (index, item) pairs, replacing manual counters and range(len(...)). zip pairs items from several iterables and stops at the shortest; zip(..., strict=True) raises a ValueError on unequal lengths, and itertools.zip_longest pads the shorter ones.

Full answer
python
from itertools import zip_longest
names = ["Asha", "Ben", "Chen"]
marks = [88, 75]
for rank, name in enumerate(names, start=1):
    print(rank, name)
print(list(zip(names, marks)))
print(list(zip_longest(names, marks, fillvalue=None)))
try:
    list(zip(names, marks, strict=True))
except ValueError as e:
    print("ValueError:", e)
print(dict(zip(names, marks)))

Output:

text
1 Asha
2 Ben
3 Chen
[('Asha', 88), ('Ben', 75)]
[('Asha', 88), ('Ben', 75), ('Chen', None)]
ValueError: zip() argument 2 is shorter than argument 1
{'Asha': 88, 'Ben': 75}

Starting enumerate at 1 gives human-friendly ranks. Plain zip silently dropped Chen because only two marks exist, which can hide data bugs; strict=True (Python 3.10+) turns that into an error, and zip_longest keeps Chen with None. dict(zip(keys, values)) is a common way to build a mapping. Both functions return lazy iterators, so wrap them in list() to see or reuse the results.

python
from itertools import zip_longest
names = ["Asha", "Ben", "Chen"]
marks = [88, 75]
for rank, name in enumerate(names, start=1):
    print(rank, name)
print(list(zip(names, marks)))
print(list(zip_longest(names, marks, fillvalue=None)))
try:
    list(zip(names, marks, strict=True))
except ValueError as e:
    print("ValueError:", e)
print(dict(zip(names, marks)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • enumerate replaces manual counters
  • zip stops at the shortest
  • strict=True catches unequal lengths
  • zip_longest pads
  • Both are lazy iterators

Common mistakes

  • Using range(len(x)) to loop
  • Losing data silently with zip

Follow-ups

  • How would you unzip a list of pairs?
  • How do you loop over two lists in parallel with indexes?

Tips

  • Mention strict=True