Optimizing Python Loops with enumerate() and zip()
Optimizing Python Loops with enumerate() and zip() ๐
When writing Python loops, combining enumerate() and zip() can help you write cleaner and more efficient code.
In this post, we'll look at how to use them separately and together with real-world examples.
✅ Using enumerate() and zip() Separately
enumerate() is great for tracking indexes.
zip() is perfect for parallel iteration over multiple sequences.
# Using enumerate and zip individually
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for i, name in enumerate(names):
print(i, name)
for name, score in zip(names, scores):
print(name, score)
✅ Combining enumerate() with zip()
Need both the index and values from two lists? This pattern keeps your code short and readable.
# Using enumerate + zip together
for i, (name, score) in enumerate(zip(names, scores)):
print(f"{i+1}. {name} - {score} points")
✅ zip Stops at the Shortest List
Keep in mind: zip() only goes as far as the shortest input list.
# zip stops at the shortest list
names = ['Alice', 'Bob']
scores = [90, 85, 77]
for i, (name, score) in enumerate(zip(names, scores)):
print(f"{i+1}. {name} - {score}")
This loop pattern is incredibly useful for data display, paired processing, or indexed output. Learn it once, use it forever.
Clean loops lead to clean logic. Write less, do more — and make every iteration count. ๐
Icons by Flaticon
Comments
Post a Comment