You can iterate over two lists (or more) in Python using a zip() function:
Here is an example of iterating over two lists (list_a and list_b) at the same time:
list_a = [1, 2, 3, 4, 5]
list_b = [5, 6, 7, 8, 9]
list_c = []
for x, y in zip(list_a, list_b):
sum_lists = x + y
list_c.append(sum_lists)
print(list_c)
The result is a third list (list_c) that contains the sum of items from the two lists:
[6, 8, 10, 12, 14]
Alternatively, you can achieve the same results using a list comprehension and a zip() function:
list_a = [1, 2, 3, 4, 5]
list_b = [5, 6, 7, 8, 9]
list_c = [(x + y) for x, y in zip(list_a, list_b)]
print(list_c)
As you can see, you’ll get the same results:
[6, 8, 10, 12, 14]
Iterate over multiple Lists in Python
You can use the same concepts to iterate over multiple lists in Python.
For instance, you can iterate over 3 lists as follows:
list_a = [1, 2, 3, 4, 5]
list_b = [5, 6, 7, 8, 9]
list_c = [2, 4, 6, 8, 10]
list_d = []
for x, y, z in zip(list_a, list_b, list_c):
sum_lists = x + y + z
list_d.append(sum_lists)
print(list_d)
Now list_d would contain the sum of items from the 3 lists:
[8, 12, 16, 20, 24]
As before, you may use a list comprehension to get the same results:
list_a = [1, 2, 3, 4, 5]
list_b = [5, 6, 7, 8, 9]
list_c = [2, 4, 6, 8, 10]
list_d = [(x + y + z) for x, y, z in zip(list_a, list_b, list_c)]
print(list_d)
The result:
[8, 12, 16, 20, 24]