Adding two Python lists elements

PythonServer Side ProgrammingProgramming

Lists can be added in python resulting in creation of a new list containing elements from both the lists. There are various approaches to add two lists and they are described below. But in all these cases the lists must be of same length.

Using Append()

Using append() we can add the elements of one list to another.

Example

 Live Demo

List1 = [7, 5.7, 21, 18, 8/3]
List2 = [9, 15, 6.2, 1/3,11]
# printing original lists
print ("list1 : " + str(List1))
print ("list2 : " + str(List2))
newList = []
for n in range(0, len(List1)):
   newList.append(List1[n] + List2[n])
print(newList)

Running the above code gives us the following result:

list1 : [7, 5.7, 21, 18, 2.6666666666666665]
list2 : [9, 15, 6.2, 0.3333333333333333, 11]
[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]

Using Map() and Add()

We can sue the map() along with the add() to add the elements of the list. The map function uses the first parameter which the add function and adds the elements of two lists which are at the same index.

Example

 Live Demo

from operator import add
#Adding two elements in the list.
List1 = [7, 5.7, 21, 18, 8/3]
List2 = [9, 15, 6.2, 1/3,11]
# printing original lists
print ("list1 : " + str(List1))
print ("list2 : " + str(List2))
NewList = list(map(add,List1,List2))
print(NewList)

Running the above code gives us the following result:

list1 : [7, 5.7, 21, 18, 2.6666666666666665]
list2 : [9, 15, 6.2, 0.3333333333333333, 11]
[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]

Using ZIp() and Sum()

In a similar approach as above we can take the zip() and the sum() using a for loop. Through the for loop we bind two elements of a list at the same index and then apply the sum() to each of them.

Example

 Live Demo

#Adding two elements in the list.
List1 = [7, 5.7, 21, 18, 8/3]
List2 = [9, 15, 6.2, 1/3,11]
result = [sum(n) for n in zip(List1, List2)]
print(result)

Running the above code gives us the following result:

[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]
raja
Published on 30-Dec-2019 14:44:57
Advertisements