Iterate Through Two Lists in Parallel in Python

  • Post category:List

Iterating through two lists in parallel in Python can be done using the zip() function. Here are two examples:

Example 1:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
for number, letter in zip(numbers, letters):
    print(f"Number: {number}, Letter: {letter}")

Output:

Number: 1, Letter: a
Number: 2, Letter: b
Number: 3, Letter: c

Example 2:

fruits = ['apple', 'banana', 'orange']
prices = [1.99, 0.99, 2.49]
for fruit, price in zip(fruits, prices):
    print(f"Fruit: {fruit}, Price: {price}")

Output:

Fruit: apple, Price: 1.99
Fruit: banana, Price: 0.99
Fruit: orange, Price: 2.49