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.