Python zip() & enumerate()
In this page:
The zip() Function
zip(list1, list2, ...) pairs up corresponding elements from multiple iterables into tuples, stopping as soon as the shortest input runs out. It's the standard way to loop over two related lists in lockstep, like names and their corresponding scores, without manually indexing into both.
Example: The zip() Function
names = ["Alex", "Sam"]
scores = [90, 80]
for name, score in zip(names, scores):
print(name, score)
Unzipping Lists
Prefixing a zipped result with * inside another zip() call unzips it back into separate lists, splitting paired tuples apart -- effectively zip() undoing its own operation, a genuinely useful but often-overlooked trick.
Example: Unzipping Lists
pairs = [(1, "a"), (2, "b")]
numbers, letters = zip(*pairs)
print(numbers, letters)
The enumerate() Function
enumerate(iterable) wraps a sequence so that looping over it yields (index, value) pairs automatically, replacing the error-prone manual pattern of maintaining a separate counter variable that you increment by hand inside the loop.
Example: The enumerate() Function
fruits = ["apple", "banana"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Custom Starting Index
Passing a start value to enumerate(iterable, start=1) begins the index count from that number instead of the default 0, useful whenever you want 1-based numbering to match how the output will actually be displayed to a person.
Example: Custom Starting Index
fruits = ["apple", "banana"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Combining zip() and enumerate()
Nesting zip() inside enumerate(), as in enumerate(zip(list1, list2)), lets you loop through multiple paired lists while also tracking a running index for each pair -- combining both patterns when you need both the position and the paired values together.
Example: Combining zip() and enumerate()
names = ["Alex", "Sam"]
scores = [90, 80]
for i, (name, score) in enumerate(zip(names, scores)):
print(i, name, score)
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects