How to Use enumerate() and zip() in Python

Python

Introduction

When working with sequences in Python, efficient iteration can save both time and lines of code. Two powerful tools for this are enumerate() and zip(). These built-in functions allow you to loop over data with indexes or in parallel, respectively.

Using enumerate(): Loop With Index

enumerate() is useful when you need both the index and the value during a loop.

colors = ['red', 'green', 'blue']

for index, color in enumerate(colors):
    print(index, color)

Output:

0 red
1 green
2 blue

You can also specify a starting index:

for i, value in enumerate(colors, start=1):
    print(i, value)

Using zip(): Loop in Parallel

zip() lets you iterate over multiple iterables simultaneously.

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 78]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

Output:

Alice: 85
Bob: 90
Charlie: 78

It’s important to note that zip() stops at the shortest iterable.

Combining Both

You can even nest these for advanced usage:

for idx, (name, score) in enumerate(zip(names, scores)):
    print(f"{idx}. {name}: {score}")

Conclusion

enumerate() and zip() are excellent tools for writing more Pythonic loops. Try them in your next project for cleaner and more readable code.

Related Links

Understanding Python Collections: List, Tuple, and Dictionary
IntroductionWorking with collections is a core part of programming in Python. Whether you're storing a list of items, gr...
Mastering Python Control Flow: if, for, and while Explained
IntroductionControl flow is the foundation of any programming language, and Python is no exception. Whether you're makin...

Comment

Copied title and URL