← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 8 of 15

Python zip() & enumerate()

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

python
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

python
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

python
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

python
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()

python
names = ["Alex", "Sam"]
scores = [90, 80]
for i, (name, score) in enumerate(zip(names, scores)):
    print(i, name, score)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.