How to Add Two Lists Elementwise in Python
Add two equal-length lists element by element using a list comprehension with zip, returning a new list of summed values.
Python code
8 linesdef elementwise_add(list1, list2):
return [a + b for a, b in zip(list1, list2)]
if __name__ == "__main__":
list_a = [1, 2, 3, 4]
list_b = [10, 20, 30, 40]
result = elementwise_add(list_a, list_b)
print(result)
Output
[11, 22, 33, 44]
How it works
The zip function pairs the i-th element of list1 with the i-th element of list2, creating tuples like (1, 10), (2, 20), etc. The list comprehension [a + b for a, b in ...] unpacks each tuple into a and b and computes their sum, producing a new list. This approach is concise and avoids manual index tracking. It assumes both lists have equal lengths; if not, zip stops at the shorter list. For unequal lists, consider using itertools.zip_longest with a fill value.
Common mistakes
- Forgetting that zip stops at the shorter list, silently ignoring extra elements
- Modifying the original lists instead of creating a new result list
- Manually iterating with indices when zip is simpler
- Attempting to use + on lists directly, which concatenates instead of adding
Variations
- Use `map` with an operator.add function: list(map(operator.add, list1, list2))
- Use a for loop with an appended result list for readability
Real-world use cases
- Combining sales totals from separate daily reports for each product into weekly figures.
- Merging sensor readings from two devices at synchronized timestamps into a single stream.
- Adding coordinate vectors in geometry or physics calculations before further analysis.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.