How To Iterate Through Two Lists In Parallel?

Summary: Use the built-in Python method zip() to iterate through two lists in parallel. The zip() method returns an iterator of tuples and the nth item of each iterator can be paired together using the zip() function. Other methods of iterating through lists in parallel include the enumerate() method and the traditional approach of iterating using a for loop.

Problem: Given two lists; how to iterate through every item of both lists simultaneously?

Example: Consider you have two lists as given in the example below.

founder = ['Steve Jobs', 'Bill Gates', 'Jeff Bezos']
org = ['Apple', 'Microsoft', 'Amazon']

print("Founder        Organization")
for f, o in some_iterator(founder,org):
  print (f,"   ", o)

Expected Output:

Founder        Organization
Steve Jobs     Apple
Bill Gates     Microsoft
Jeff Bezos     Amazon

In the above example, we need some iterator or method to generate the expected output in order to print the items of the lists in pairs one by one. So without further delay let us dive into the solutions.

Method 1: Using zip()

As the name suggests the zip() function is a built-in function in Python that returns a zip object which represents an iterator of tuples. It allows us to pair together with the first item in each iterator, and then pair the second item in each iterator and so on.

❖ zip() In Python 3 vs Python 2

  • zip() in Python 3 returns an iterator of tuples, whereas zip() in Python 2 returns a list of tuples.
  • To get a list of tuples using zip() in Python 3 use list(zip(f, o))
  • To get an iterator of tuples using zip() in Python 2 use itertools.izip

β—ˆ Note: zip() stops iterating once the shorter list among the given iterables is exhausted. Let us have a look at what that means in the example given below.

li_1 = ['a', 'b', 'c']
li_2 = [1,2]
for f, o in zip(li_1, li_2):
  print(f, o)

Output:

a 1
b 2

βž₯ In the above example zip() stopped iterating once the shorter list that is li_2 was exhausted, hence, the element c was not included in the output. Therefore, in order to iterate until the longest iterator use:

  • itertools.zip_longest() if you are using Python 3.
  • itertools.izip_longest if you are using Python 2.
  • In each case, we have to import the itertools module.

Example:

import itertools
li_1 = ['a','b','c']
li_2 = [1,2]
for f, o in itertools.zip_longest(li_1, li_2):
  print(f, o)

Output:

a 1
b 2
c None

Now that we know how to use the zip() method in Python, let us have a look at how we can use it to solve our problem in the program given below.

founder = ['Steve Jobs', 'Bill Gates', 'Jeff Bezos']
org = ['Apple', 'Microsoft', 'Amazon']

print("Founder        Organization")
for f, o in zip(founder, org):
  print (f,"   ", o)

Output:

Founder        Organization
Steve Jobs     Apple
Bill Gates     Microsoft
Jeff Bezos     Amazon

Method 2: Using For Loop

Another approach to iterate through both lists in parallel is to use a for loop. Though this might not be the most Pythonic solution to our problem, it does serve the purpose. Let us have a look at the following program to understand how we can use the for loop to solve our problem.

Example:

founder = ['Steve Jobs', 'Bill Gates', 'Jeff Bezos']
org = ['Apple', 'Microsoft', 'Amazon']

print("Founder        Organization")
for i in range(len(founder)):
  print(founder[i],"   ",org[i])

Output:

Founder        Organization
Steve Jobs     Apple
Bill Gates     Microsoft
Jeff Bezos     Amazon

Given below is a one-line solution for the above method:

founder = ['Steve Jobs', 'Bill Gates', 'Jeff Bezos']
org = ['Apple', 'Microsoft', 'Amazon']

print([( founder[i], org[i]) for i in range(len(founder))])

Output:

[('Steve Jobs', 'Apple'), ('Bill Gates', 'Microsoft'), ('Jeff Bezos', 'Amazon')]

Method 3: Emulating zip() Using A Custom Function

The best practice to iterate through two lists in parallel is to use the zip() function that has been mentioned earlier. You can also emulate the functioning of the zip() method by creating your own custom function with the yield keyword to return the items of both lists in pairs.

βž₯ yield is a keyword similar to the return keyword, but in case of yield the function returns a generator. To read more about the yield keyword in Python, please follow our blog tutorial here.

Now, let us have a look how we can define our custom function to iterate through multiple list items simultaneously.

founder = ['Steve Jobs', 'Bill Gates', 'Jeff Bezos']
org = ['Apple', 'Microsoft', 'Amazon']
count = len(founder)

def custom_zip():
    global count
    it1 = iter(founder)
    it2 = iter(org)
    try:
      while count>0:
          yield next(it1), next(it2)
          count = count -1
    except:
      raise StopIteration

for item in custom_zip():
       print(list(item))

Output:

['Steve Jobs', 'Apple']
['Bill Gates', 'Microsoft']
['Jeff Bezos', 'Amazon']

Method 4: Using enumerate()

The enumerate() method in Python, adds a counter to an iterable like a tuple or a list and returns it as an enumerate object. We can use to iterate through the lists in parallel as shown in the program below.

founder = ['Steve Jobs', 'Bill Gates', 'Jeff Bezos']
org = ['Apple', 'Microsoft', 'Amazon']
count = len(founder)
print("Founder        Organization")
for n, f in enumerate( founder ):
  print(f,"   ",org[n] )

Output:

Founder        Organization
Steve Jobs     Apple
Bill Gates     Microsoft
Jeff Bezos     Amazon

In case you are still using Python 2.x, then you can also use the map() function with the first argument as None and then iterate through both lists in parallel. I have not included this method in our list of solutions because, if you are using Python 3.x then this solution won’t work as you will get a TypeError. Yet, just for the sake of understanding let us have a look at the usage of the map method for an older version of Python.

Example:

a = ['A', 'B', 'C']
b = ['I', 'II', 'III']
for x, y in map(None, a, b):
    print(x, y)

Output In Python 2.x:

('A', 'I')
('B', 'II')
('C', 'III')

Output In Python 3.x:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    for x, y in map(None,a, b):
TypeError: 'NoneType' object is not callable

Conclusion

The key take-aways from this article were:

  • How to iterate through two lists in Python using the following methods:
    • The zip() method:
      • What is the difference while using zip() in Python 3 and Python 2?
      • The importance of itertools.zip_longest().
    • for loop.
    • enumerate() method.
    • By emulating the zip() function using a custom function.
    • Using the map() method in Python 2.x.

Please subscribe and stay tuned for more interesting articles!