Python for loops—enumerate & zip
By: Hause Lin
Tags: Programming, Artificial Intelligence, Machine Learning, Software Engineering, Data Science

Two Simple Ways to Loop More Effectively in Python

Use enumerate and zip to write better Python loops

Many loops. Photo by David Streit on Unsplash

The Python range function is very powerful, but it can often be replaced with other built-in functions that make your loops easier to write and read. In this article, I’ll show you when you can replace range with enumerate or zip .

Use enumerate(object) instead of range(len(object))

Problem 1: You often have objects like lists you want to iterate over while also keeping track of the index of each iteration. Given the list below, how would you use a for loop to generate the desired output?

my_list = ['apple', 'orange', 'cat', 'dog'] # desired output

Item 0: apple

Item 1: orange

Item 2: cat

Item 3: dog

Solution 1: Use for i in range(len(my_list))

for i in range(len(my_list)):

print(f"Item {i}: {my_list[i]}") Item 0: apple

Item 1: orange

Item 2: cat

Item 3: dog

Better solution: Use for i, value in enumerate(my_list)

for i, value in enumerate(my_list):

print(f"Item {i}: {value}") Item 0: apple

Item 1: orange

Item 2: cat

Item 3: dog

Explanation: enumerate loops over the iterator my_list and returns both the item and its index as an index-item tuple as you iterate over your object (see code and output below to see the tuple output). We unpack the index-item tuple when we construct the loop as for i, value in enumerate(my_list) .

for i in enumerate(my_list):

print(i) (0, 'apple') # tuple, which can be unpacked (see code chunk above)

(1, 'orange')

(2, 'cat')

(3, 'dog')

Problem 2: Given the same list as above, write a loop to generate the desired output (ensure the first index begins at 101 instead of 0).

my_list = ['apple', 'orange', 'cat', 'dog'] # desired output

Item 101: apple

Item 102: orange

Item 103: cat

Item 104: dog

Solution 2: Use for i, value in enumerate(my_list, 101)

The function enumerate(iterable, start=0) lets you start counting the index at any desired number (default is 0).

for i, value in enumerate(my_list, 101):

print(f"Item {i}: {value}") Item 101: apple

Item 102: orange

Item 103: cat

Item 104: dog

Takeaways

The enumerate built-in function loops over an iterator and returns the index and the item as an index-item tuple from the iterator as you go

built-in function loops over an iterator and returns the index and the item as an index-item tuple from the iterator as you go Use enumerate(object) instead of range(len(object)) for more concise and readable code

instead of for more concise and readable code Provide a second parameter to indicate the number from which to begin counting (0 is the default)

Use zip to iterate multiple objects in parallel

Problem 3: You have multiple lists or objects you want to iterate in parallel. Given the three lists below, how would you produce the desired output?

my_list = ['apple', 'orange', 'cat', 'dog']

my_list_n = [11, 12, 25, 26]

my_list_idx = [1, 2, 3, 4] # desired output

1. apple: 11

2. orange: 12

3. cat: 25

4. dog: 26

Solution 3: Use range(len(my_list)) to get the index

for i in range(len(my_list)):

print(f"{my_list_idx[i]}. {my_list[i]}: {my_list_n[i]}") 1. apple: 11

2. orange: 12

3. cat: 25

4. dog: 26

Better solution: Use zip(my_list_idx, my_list, my_list_n)

for i, obj, count in zip( my_list_idx , my_list , my_list_n ):

print(f"{i}. {obj}: {count}") 1. apple: 11

2. orange: 12

3. cat: 25

4. dog: 26

Explanation: You can use zip to iterate over multiple objects at the same time. zip returns tuples that can be unpacked as you go over the loop. See examples below to understand how this function works.

zip returns tuples:

for i in zip(my_list_idx, my_list, my_list_n):

print(i) (1, 'apple', 11) # 3-item tuple

(2, 'orange', 12)

(3, 'cat', 25)

(4, 'dog', 26)

Each element within the tuple can be extracted manually:

for i in zip(my_list_idx, my_list, my_list_n):

print(f"{i[0]}. {i[1]}: {i[2]}") # i is a 3-item tuple 1. apple: 11

2. orange: 12

3. cat: 25

4. dog: 26

Takeaways

The zip built-in function can iterate over multiple iterators at the same time.

built-in function can iterate over multiple iterators at the same time. zip creates a lazy generator that produces tuples

Conclusion

Using the built-in Python functions enumerate and zip can help you write better Python code that’s more readable and concise.

If you are interested in improving your data science skills, the following articles might be useful:

For more posts, subscribe to my mailing list.