Python / Core Python Fundamentals Interview Questions
How do enumerate() and zip() make loops more Pythonic?
Both functions are loop helpers that eliminate boilerplate index management and make the intent of the code clearer.
enumerate(iterable, start=0) yields (index, value) pairs. Instead of maintaining a counter variable, you unpack it directly in the loop header:
# Non-Pythonic i = 0 for name in names: print(i, name) i += 1 # Pythonic with enumerate for i, name in enumerate(names, start=1): print(i, name)
zip(*iterables) pairs up elements from two or more iterables by position and stops at the shortest one. It is lazy — returns a zip iterator, not a list.
keys = ['name', 'age', 'city'] values = ['Alice', 30, 'NYC'] for k, v in zip(keys, values): print(f'{k}: {v}') # Build a dict from two parallel lists record = dict(zip(keys, values)) # {'name': 'Alice', 'age': 30, 'city': 'NYC'} # zip stops at the shortest â use itertools.zip_longest for full coverage from itertools import zip_longest for a, b in zip_longest([1, 2, 3], [10, 20], fillvalue=0): print(a, b) # 1 10 / 2 20 / 3 0
Combining both: for i, (k, v) in enumerate(zip(keys, values)): gives you the index and the pair simultaneously. These two functions together eliminate the vast majority of situations where you would otherwise manage index variables manually, and they make code easier to read and harder to get wrong.
More Related questions...