Sling Academy
Home/Python/List element-wise operations in Python

List element-wise operations in Python

Last updated: July 04, 2023

List element-wise operations refer to performing operations on corresponding elements of multiple lists in a pairwise manner. These operations allow you to apply a function or operator to elements at the same index position in two or more lists, resulting in a new list with the computed values.

In this concise example-based article, we’ll use list comprehensions and built-in functions like zip() to efficiently perform element-wise operations on lists of equal lengths.

Addition (+)

This code adds corresponding elements of two or more lists:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [x + y for x, y in zip(list1, list2)]
print(result)

Output:

[5, 7, 9]

Subtraction (-)

The example below subtracts the corresponding elements of two or more lists:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [x - y for x, y in zip(list1, list2)]
print(result)

Output:

[-3, -3, -3]

Multiplication (*)

This example demonstrates how to multiply the corresponding elements of two given lists:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [x * y for x, y in zip(list1, list2)]
print(result)

Output:

[4, 10, 18]

Division (/)

Here’s how to divide the corresponding elements of two given lists:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [x / y for x, y in zip(list1, list2)]
print(result)

Output:

[0.25, 0.4, 0.5]

If list2 contains 0, then ZeroDivisionError: division by zero will occur.

Next Article: Python: Define Generic Types for Multidimensional List

Previous Article: Python: Generate a Dummy List with N Random Elements

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • 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
  • Monitoring Order Book Imbalances for Trading Signals via cryptofeed
  • Detecting Arbitrage Opportunities Across Exchanges with cryptofeed