Sling Academy
Home/Python/Python: How to loop through 2 lists in parallel (3 ways)

Python: How to loop through 2 lists in parallel (3 ways)

Last updated: June 19, 2023

This concise, example-based article will walk you through some different ways to iterate over 2 Python lists in parallel. Without more delays, let’s get started.

Using the zip() function

The zip() function combines the elements of 2 or more lists into tuples, allowing you to iterate over them in parallel. It will stop when the shortest list is exhausted and ignore any remaining elements in the longer list.

Example:

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']

for item1, item2 in zip(list1, list2):
    print(item1, item2)

Output:

1 a
2 b
3 c
4 d
5 e

Using enumerate() with indexing

This approach uses the enumerate() function along with indexing to access corresponding elements in both lists.

Code example:

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']

for index, item1 in enumerate(list1):
    if index < len(list2):
        item2 = list2[index]
        print(item1, item2)

Output:

1 a
2 b
3 c

The advantage of this approach is that it allows for more flexibility in handling lists of different lengths, as you have control over the indexing.

Using the itertools.zip_longest() function

zip_longest() is a function from the itertools module that allows you not only to iterate over multiple iterables in parallel but also to fill in missing values with a specified fill value when the iterables are of different lengths. While the zip() function stops immediately when the shortest list is exhausted, the itertools.zip_longest() function will go forward until the end of the longest list.

Example:

from itertools import zip_longest

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']

for item1, item2 in zip_longest(list1, list2, fillvalue="Sling Academy"):
    print(item1, item2)

Output:

1 a
2 b
3 c
4 Sling Academy
5 Sling Academy

That’s it. Happy coding!

Next Article: Python map() function: Tutorial & examples

Previous Article: Python: Count the Occurrences of Elements in a List (3 Ways)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots