How to iterate over two lists or more in python ?


Examples of how to iterate over two lists or more in python

Iterate over two lists of same size

A simple solution is to use the function zip

>>> l1 = ['a','b','c']
>>> l2 = [1,2,3]
>>> for x,y in zip(l1,l2):
...     print(x,y)
... 
a 1
b 2
c 3

Iterate over three lists of same size

Another example:

>>> l1 = ['a','b','c']
>>> l2 = [1,2,3]
>>> l3 = ['hello','hi','bye']
>>> for x,y,z in zip(l1,l2,l3):
...     print(x,y,z)
... 
a 1 hello
b 2 hi
c 3 bye

Iterate over lists of different sizes

An example of solution to iterate over two lists of different sizes

>>> l1 = ['a','b','c','d','e','f']
>>> l2 = [1,2,3]
>>> min_length = min(len(l1), len(l2))
>>> for x,y in zip(l1[:min_length],l2[:min_length]):
...     print(x,y)
... 
a 1
b 2
c 3

References