Home >Backend Development >Python Tutorial >What\'s the Most Efficient Way to Perform Element-Wise Addition of Lists in Python?
Element-Wise Addition of Lists: A Pythonic Approach
Adding two lists element-wise can be performed effortlessly in Python using several built-in functions. Here's how to achieve this without cumbersome iterations:
Using map() with operator.add:
from operator import add result = list(map(add, list1, list2))
The map() function applies the add function to each corresponding element in list1 and list2, returning a list of the results.
Alternatively, using zip() with a list comprehension:
result = [sum(x) for x in zip(list1, list2)]
The zip() function pairs up the elements from list1 and list2 into a sequence of tuples. The list comprehension then calculates the sum of each tuple, producing the element-wise addition.
Performance Comparisons:
To compare the efficiency of these approaches, we conducted timing tests on large lists (100,000 elements):
>>> from itertools import izip >>> list2 = [4, 5, 6] * 10 ** 5 >>> list1 = [1, 2, 3] * 10 ** 5 >>> %timeit from operator import add; map(add, list1, list2) 10 loops, best of 3: 44.6 ms per loop >>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)] 10 loops, best of 3: 71 ms per loop >>> %timeit [a + b for a, b in zip(list1, list2)] 10 loops, best of 3: 112 ms per loop >>> %timeit from itertools import izip; [sum(x) for x in izip(list1, list2)] 1 loops, best of 3: 139 ms per loop >>> %timeit [sum(x) for x in zip(list1, list2)] 1 loops, best of 3: 177 ms per loop
As these results demonstrate, the map() approach using operator.add is the fastest for large lists.
The above is the detailed content of What\'s the Most Efficient Way to Perform Element-Wise Addition of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!