Iterate Over Two Lists in Python

Iterate Over Two Lists in Python

  1. Iterate Over Two Lists in Python
  2. Use the zip() Function to Iterate Over Two Lists in Python
  3. Use the izip() Function to Iterate Over Two Lists in Python
  4. Use the map() Function to Iterate Over Two Lists in Python
  5. Use the zip_longest() Function to Iterate Over Two Lists in Python

While parsing the data stored in data structures such as dictionary, tuple, list, we come across iteration to move over the data sequence stored in it.

Iterating a single data structure like a list in Python is common, but what if we come across a scenario that expects us to iterate over two/multiple lists together?

This article will unveil the different ways to iterate over two lists in Python with some demonstrations.

Iterate Over Two Lists in Python

We can iterate over a single Python list using a for loop or a range() function.

The range(start, stop, step) function enables us to get a sequence of numbers from a defined range of values. It accepts start, stop, and step as input.

Where:

  • The start index is where the range() function starts to iterate and get the numbers or elements.
  • The stop index determines the position or integer where the iteration of the sequence of elements should stop.
  • The step index is an optional parameter that allows us to include patterns such as increments in the iteration of the sequence of elements in the list.

Consider the example below. We declare a list with some arbitrary values and then loop in the list using any in-built function such as range().

lst = [10, 2, 0, 1]
for x in range(0, 4):
   print("Iteration through a single list:", lst[x])

Output:

Iteration through a single list: 10
Iteration through a single list: 2
Iteration through a single list: 0
Iteration through a single list: 1

Here, we have passed the start index to the function as 0 so that it starts to get the sequence of elements from the list right from position 0, i.e., the first element.

The stop index is set as 4, equivalent to the list length, so that the range() function iterates the sequence until the last element and displays it.

Isn’t that simple? And, if we have more than one list to iterate in parallel?!

Well, having recalled the iteration of a single list, let us now understand different ways through which we can iterate two Python lists.

Use the zip() Function to Iterate Over Two Lists in Python

Python zip function enables us to iterate over two or more lists by running until the smaller list gets exhausted.

The zip function accepts multiple lists, strings, etc., as input. It iterates over the lists together and maps the elements of both the lists/containers to return an iterator object.

Consider the below scenario.

We have two lists for iteration indicated in the code. We pass the lists list01 and list02 as input to the zip() function.

The zip() function then iterates over the two lists in parallel only 2 times the length(list02)=2. It maps the elements of both the lists in a clubbed or tuple format to return an iterator object.

So, the expected output is 1, x and 2, y.

This is how we can iterate over two lists using the zip() function.

import itertools

list01 = [1, 2, 3, 4, 5]
list02 = [10, 20]

for (i,j) in zip(list01, list02):
    print (i,j)

Output:

1 10
2 20

Use the izip() Function to Iterate Over Two Lists in Python

To use a version before Python 3.0, we use the izip() function instead of the zip() function to iterate over multiple lists.

The izip() function also expects a container such as a list or string as input. It iterates over the lists until the smallest of them gets exhausted.

It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.

Let us have a look at the below example.

from itertools import izip

list01 = [1, 2, 3, 4, 5]
list02 = [10, 20]

for (i,j) in izip(list01, list02):
	print (i,j)

Output-

(1, 10)
(2, 20)

We have declared two lists, list01 and list02, with some data values. We then use the izip() function to iterate over the lists.

Here, this function accepts the two lists as input, maps the data elements of both the lists position-wise, and then returns an iterator object, the tuple of data elements of both the lists.

Note that with Python 3 and above versions, the zip() function returns an iterator value while the izip() function stands to be obsolete. So, the izip() function in Python version 2.x is similar to the zip() function in Python 3 and above.

Use the map() Function to Iterate Over Two Lists in Python

Apart from the zip() function, Python also offers us the map() function to iterate over multiple lists until all the list elements are exhausted.

Unlike the zip() function, the map() function does not consider only the smallest of all lists. Instead, it accounts for the varied length of lists altogether.

The map() function accepts iterable data structures such as lists and strings as input along with a function. After applying the specified function, it maps the iterable data elements and returns a tuple after mapping the values.

list01 = [1, 2, 3, 4, 5]
list02 = [10, 20]

for (i,j) in map(None, list01, list02):
    print (i,j)

Output:

(1, 10)
(2, 20)
(3, None)
(4, None)
(5, None)

As seen above, it iterated throughout the length of the entire two lists and mapped the first list’s elements with the other list’s element.

As soon as it does not find any element at that position, it returns a None and attaches it to the mapping element at that position.

For example, the map() function tried to map element 3 of list01 with an element at the similar index (position) of list02.

Since it did not find any element, it mapped and formed a match with None. Thus, we see the output pair (3, None).

Also, a notable difference between zip() and map() is that the length of the list generated as an output of the zip() function is equal to the length of the smallest list. On the other hand, the latter does not follow those criteria.

The map function works as expected in Python 2. However, in Python 3 and above, we can use the zip_longest function to achieve the same result.

Use the zip_longest() Function to Iterate Over Two Lists in Python

The zip_longest() function is a replacement of the map() function available in Python version 2. It accepts iterable objects such as lists and strings as input.

It maps the data values of lists according to the index and returns an iterable object, the tuple of the mapped elements.

Similarly, it iterates over two lists until all the elements of both lists are exhausted. Also, in the output, it maps an element of list 01 with another element of list 02.

If one of the lists gets exhausted of elements, it replaces them with None.

Consider the below example.

import itertools

list01 = [1, 2, 3]
list02 = ['x','y']

for (i,j) in itertools.zip_longest(list01, list02):
    print (i,j)

Output:

1 x
2 y
3 None

In the above example, when the iteration cycle maps the second elements of both lists and moves to the third element, we see that list02, a list of 2 elements, gets exhausted.

In this case, the zip_longest() function replaces and maps the equivalent element with a None value.

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • What Is the Difference Between List Methods Append and Extend
  • Convert a List to String in Python