Python Advanced
Python enumerate and zip
enumerate() and zip() are two small but powerful built-in functions that make loops cleaner: one gives you the index alongside each value, the other pairs up multiple lists at once.
enumerate() — Index and Value
Normally, looping over a list only gives you the value. If you also need the position of each item, wrap the list in enumerate(), which returns pairs of (index, value) that you can unpack directly in the for loop.
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)0 apple
1 banana
2 mangoYou can also start counting from a number other than zero by passing a start argument, which is handy for user-facing numbering like "Item 1", "Item 2".
for position, fruit in enumerate(fruits, start=1):
print(f"{position}. {fruit}")zip() — Pairing Iterables
zip() takes two or more iterables and combines them element by element into tuples, stopping as soon as the shortest iterable runs out. It is perfect for looping over related lists together, like names and scores.
names = ["Aarav", "Priya", "Rohan"]
scores = [88, 92, 76]
for name, score in zip(names, scores):
print(f"{name} scored {score}")zip() stops at the shortest input, so if your lists have different lengths, the extra items in the longer list are silently ignored.
Unzipping
You can also reverse the process: unpack a zipped set of pairs back into separate tuples using zip() together with the unpacking operator *.
pairs = [("Aarav", 88), ("Priya", 92), ("Rohan", 76)]
names, scores = zip(*pairs)
print(names)
print(scores)('Aarav', 'Priya', 'Rohan')
(88, 92, 76)| Function | Purpose |
|---|---|
| enumerate(iterable) | Adds an index to each item while looping |
| zip(a, b, ...) | Combines multiple iterables into tuples |
| zip(*pairs) | Unzips a list of tuples back into separate groups |
Both enumerate() and zip() return iterator objects, so wrap them in list() if you need to see or reuse all the results at once.
