Python 3: Simultaneously Iterating over Multiple Sequences

Last updated on November 10, 2021 Pennywise Loading... Post a comment

The example below shows you how to iterate through multiple sequences in Python 3 with just a single for loop. The trick here is to use the zip() function to zip up the elements of a number of lists, tuples, or other sequences.

Example

animals = ['dog', 'cat', 'crocodile', 'bear', 'penguin']
fruits = ['apple', 'banana', 'coconut', 'orange', 'guava']
colors = ['red', 'yellow', 'white', 'orange', 'green']

for i, (animal, fruit, color) in enumerate((zip(animals, fruits, colors))):
    print(f'{i}: {animal} - {fruit} - {color}')

Output:

0: dog - apple - red
1: cat - banana - yellow
2: crocodile - coconut - white
3: bear - orange - orange
4: penguin - guava - green

It’s worth noting that the zip() function can take an arbitrary number of sequences, and the number of elements it produces is determined by the shortest sequence.

Further reading

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like