/  Technology   /  How to iterate through two lists in parallel in Python?
How to iterate through two lists in parallel in Python

How to iterate through two lists in parallel in Python?

 

Iteration over a single list means iterating over a single element from a single list using a for loop at a particular step, whereas iterating over multiple lists simultaneously means iterating over a single element from multiple lists using a for loop at a particular step. 

  • Using zip()
  • Using itertools.zip_longest()
  • Using for loop

 

Using zip():

The zip() function takes a sequence(any iterable) as a parameter and returns an iterable. This function stops working when any one of the given two lists exhausts. This means that the function stops after it’s done iterating the smallest list. 

 

Example:

list_1= ['One', 'Two', 'Three']
list_2= ['Four', 'Five']

for (x, y) in zip(list_1,list_2):
   print (x, y)

Output:

 

Using itertools.zip_longest():

This function takes in iterables as parameters. It works until all the given lists are exhausted. Once the shorter list is exhausted, this function returns a tuple with None value. We’ll have to import the itertools module to implement this function.

 

Example:

import itertools

list_1= ['One', 'Two', 'Three']
list_2= ['1', '2']

for (x, y) in itertools.zip_longest(list_1,list_2):
   print (x, y)

Output:

 

We can also give custom values for the shorter list once it’s exhausted by assigning that value to fillvalue and passing it as a parameter.

 

Example:

import itertools

list_1= ['One', 'Two', 'Three']
list_2= ['1', '2']

for (x, y) in itertools.zip_longest(list_1,list_2, fillvalue=0):
   print (x, y)

Output:

 

Using for loop:

 

Example:

list_1= ['One', 'Two', 'Three']
list_2= ['Four', 'Five', 'Six']

for i in range(len(list_1)):
   print (list_1[i],list_2[i])

Output:

 

Leave a comment