Introduction
Looping in Python is more than just for i in range()
. With tools like enumerate()
and zip()
, you can write cleaner, more expressive code when working with multiple sequences or when tracking indexes. This article walks through how and when to use these loop enhancements effectively.
Using enumerate() to Track Index and Value
The enumerate()
function lets you iterate over a list while also keeping track of the index:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
This is cleaner than using range(len(...))
and avoids common bugs related to indexing.
Customizing the Starting Index
You can change the starting index by passing a second argument:
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
Using zip() to Loop Over Multiple Sequences
The zip()
function combines two or more sequences into pairs:
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
If the sequences are not the same length, zip()
stops at the shortest one.
Converting zip Output to a List
You can also use zip()
to create dictionaries or lists:
result = list(zip(names, scores))
print(result)
# Output: [('Alice', 85), ('Bob', 90), ('Charlie', 78)]
Conclusion
Both enumerate()
and zip()
are great tools for improving loop readability and reducing code complexity. These are essential for any Python developer aiming to write clean, maintainable code.
Comment