How to iterate through two Python lists in parallel?

In this short article, we present you an elegant method to loop (iterate) over two Python lists in parallel.

We can iterate throught two list using for loop and Python built-in zip() function.

Python Source Code: Iterating Parallelly


# List 1
fruits = ['apple', 'banana', 'grapes', 'orange', 'kiwi']
# List 2
prices = [200, 100, 240, 80, 400]

# Parallel iteration
for (f,p) in zip(fruits, prices):
    print(f,p)

Output

apple 200
banana 100
grapes 240
orange 80
kiwi 400

Understanding zip() Function

Let's understand working of built-in function zip() using following program having three different cases:


a = [1, 2, 3]
b = [11, 12, 13]
c = [11, 12, 13, 14]
d = [11, 12]

x =zip(a,b)
y = zip(a,c)
z = zip(a,d)
print('x = ', *x)
print('y = ', *y) 
print('z = ', *z)

Output

x =  (1, 11) (2, 12) (3, 13)
y =  (1, 11) (2, 12) (3, 13)
z =  (1, 11) (2, 12)

Note: zip() stops its operation when end of either collection is reached.