Tutorial Example

Loop Through Two Lists At the Same Time in Python – Python Tutorial

In this tutorial, we will introduce how to loop through tow or multiple lists at the same time in python, which is very useful when you want to get list value by the same list index.

We can use python zip() function to loop through. To understand how to use zip() function, you can view:

Understand Python zip() Function – Python Tutorial

How to use zip() to loop through two lists in python?

Look at the example below:

lx = [2, 3, 4]
ly = [4, 5, 6]

for x, y in zip(lx, ly):
    print(x, y

Run this code, we will get this result:

2 4
3 5
4 6

How about the length of two lists are not the same?

For example:

lx = [2, 3, 4]
ly = [4, 5, 6, 7]

for x, y in zip(lx, ly):
    print(x, y)

In this example, the length of lx is 3, the length of ly is 4, they are not the same. Run this code, you will find the result is:

2 4
3 5
4 6

The number 7 in ly is ignored.