How to use the zip() function in a loop in Python?

Published on Aug. 22, 2023, 12:18 p.m.

To use the zip() function in a loop in Python, you can pass multiple iterables as arguments to the zip() function, which returns an iterator that contains tuples of corresponding elements from all the iterables. You can then use the iterator in a loop to process the tuples. Here’s an example code snippet that demonstrates how to use zip() in a loop:

list1 = [1,2,3]
list2 = ['a','b','c']
list3 = ['foo','bar','baz']

for item1, item2, item3 in zip(list1, list2, list3):
    print(f"{item1} {item2} {item3}")

In this example, the zip() function is used to create an iterator that returns tuples containing corresponding elements from three iterables, list1, list2 and list3. The for loop then iterates over this iterator, unpacks the tuples into separate variables item1, item2, and item3, and prints each item together. The output of the above code will be:

1 a foo
2 b bar
3 c baz

This shows that each iteration of the loop processes a tuple with corresponding elements from all three iterables.

Tags: