Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Adding two Python lists elements
In Python, a list is a built-in data structure that stores an ordered collection of multiple items in a single variable. Lists are mutable, meaning we can add, remove, and change their elements. This article demonstrates how to add corresponding elements of two Python lists element-wise.
Given two equal-sized lists, we need to create a new list containing the sum of corresponding elements from both lists.
Example Scenario
# Input lists list1 = [3, 6, 9, 45, 6] list2 = [11, 14, 21, 0, 6] # Expected output: [14, 20, 30, 45, 12] # Explanation: 3+11=14, 6+14=20, 9+21=30, 45+0=45, 6+6=12
Using For Loop
Iterate through both lists and add corresponding elements using a for loop with append() ?
list1 = [7, 5.7, 21, 18, 8/3]
list2 = [9, 15, 6.2, 1/3, 11]
new_list = []
for i in range(len(list1)):
new_list.append(list1[i] + list2[i])
print(new_list)
[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]
Using map() and add() Functions
The map() function applies the add() operation to corresponding elements of both lists ?
from operator import add list1 = [7, 5.7, 21, 18, 8/3] list2 = [9, 15, 6.2, 1/3, 11] new_list = list(map(add, list1, list2)) print(new_list)
[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]
Using zip() Function
The zip() function pairs corresponding elements, then sum() adds each pair ?
list1 = [7, 5.7, 21, 18, 8/3] list2 = [9, 15, 6.2, 1/3, 11] result = [sum(pair) for pair in zip(list1, list2)] print(result)
[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]
Using NumPy Library
NumPy provides efficient array operations for numerical computing. The np.add() function adds corresponding elements ?
import numpy as np list1 = [1, 3, 4, 6, 8] list2 = [4, 5, 6, 2, 10] result = np.add(list1, list2) print(result)
[ 5 8 10 8 18]
Comparison
| Method | Best For | Performance |
|---|---|---|
| For Loop | Small lists, learning | Moderate |
| map() + add() | Functional programming | Good |
| zip() + sum() | Readable, Pythonic | Good |
| NumPy | Large arrays, scientific computing | Excellent |
Conclusion
Use NumPy for large datasets and scientific computing due to its superior performance. For small lists, zip() provides the most Pythonic approach, while for loops offer the most readable solution for beginners.
