Skip to the solution
EasyDSA9 min read

What do enumerate and zip do?

348 views

The problem

Question presented to candidate: "I often see loops like for i in range(len(items)). What do enumerate and zip do, how would you use them to clean that up, and is there anything surprising about how they behave?"

What a strong answer should cover:

  • enumerate(iterable, start=0) yields (index, item) pairs, so you never index back into the list; start= sets the first number.
  • zip(a, b, ...) yields tuples that take one item from each input, and stops as soon as the shortest input runs out.
  • Both return lazy, single-use iterators (iter(e) is e), not lists; they work on any iterable, including generators and infinite ones.
  • zip(..., strict=True) (Python 3.10, PEP 618) raises ValueError on a length mismatch; itertools.zip_longest pads instead.
  • Idioms: dict(zip(keys, values)), zip(*rows) to transpose or unzip, enumerate(zip(a, b)) for index plus pairs.
  • The lost-item gotcha: zip pulls from the left input first, so an iterator passed on the left loses one item when a later input runs out.

Code / implementation expected: Yes β€” rewrite an index loop with enumerate, walk two lists with zip, and show zip(*rows) or dict(zip(...)).

  • enumerate
  • zip

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonenumerate, zip, dict(zip(...)), transpose and unzip
PythonGotchas: single use, strict=True, zip_longest, the lost item, chunking

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 29 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What values are falsy in Python?

Continue