Computer >> Computer tutorials >  >> Programming >> Python

How to loop through multiple lists using Python?


The most straightforward way seems to use an external iterator to keep track. Note that this answer considers that you're looping on same sized lists. 

example

a = [10, 12, 14, 16, 18]
b = [10, 8, 6, 4, 2]

for i in range(len(a)):
   print(a[i] + b[i])

Output

This will give the output −

20
20
20
20
20

Example

You can also use the zip method that stops when the shorter of a or b stops.

a = [10, 12, 14, 16, 18]
b = [10, 8, 6]

for (A, B) in zip(a, b):
   print(A + B)

Output

This will give the output −

20
20
20