Python Program to Iterate Through Two Lists in Parallel – 2022

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Iterate Through Two Lists in Parallel.

Example 1: Using zip (Python 3+)

# Python Program to Iterate Through Two Lists in Parallel

list_1 = ['a', 'b', 'c']
list_2 = [1, 2, 3, 4]

for i, j in zip(list_1, list_2):
    print(i, j)

Output

a 1
b 2
c 3
  • Here we have used the zip method to bind two lists.
  • Zipping list_1 and list_2 will create a new list like [(‘a’,1),(‘b’,2),(‘c’,3)].
  • Then we are simply traversing in the zipped list and printing elements.

Example 2: Using itertools (Python 2+)

import itertools

list_1 = ['a', 'b', 'c']
list_2 = [1, 2, 3, 4]

# loop until the short loop stops
for i,j in zip(list_1,list_2):
    print(i,j)

print("\n")

# loop until the longer list stops
for i,j in itertools.zip_longest(list_1,list_2):
    print(i,j)

Output

a 1
b 2
c 3


a 1
b 2
c 3
None 4
  • Here also first of all we are using zip.
  • In the second example, we are using itertools.zip_longest() which will zip according to the longest list of the 2 provided.
  • In the shorter list, it will add None as shown above in the output.

Check out our other python programming examples

Leave a Comment

Your email address will not be published. Required fields are marked *