Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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
Updated on: 2020-03-05T08:06:15+05:30

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements