752
In this article, we will show you how to add two lists in python.
There are a few ways to add two lists of elements in python.
We will show you 3 different ways to perform add two lists in python.
Example 1
The first example we use a for loop to iterate and append the sum of the element to the new list
# Add Two Lists list1 = [10, 20, 30, 40, 50] list2 = [5, 10, 15, 20, 25] total = [] for j in range(5): total.append(list1[j] + list2[j]) print("The Sum of the Two Lists = ", total)
You will see the following
>>> %Run add2lists1.py The Sum of the Two Lists = [15, 30, 45, 60, 75]
Example 2
This example uses list comprehension
# Python Program to Add Two Lists Using List Comprehension method list1 = [10, 20, 30, 40, 50] list2 = [5, 10, 15, 20, 25] total = [] print ("List 1 : " + str(list1)) print ("List 2 : " + str(list2)) # using list comprehension to add the two lists total = [list1[i] + list2[i] for i in range(len(list1))] # printing resultant list print ("Resultant list is : " + str(total))
You will see the following
>>> %Run add2lists2.py List 1 : [10, 20, 30, 40, 50] List 2 : [5, 10, 15, 20, 25] Resultant list is : [15, 30, 45, 60, 75]
Example 3
This example uses addition of two lists using the map() function
# Add two Lists using map() with add operator from operator import add # initializing lists list1 = [10, 20, 30, 40, 50] list2 = [5, 10, 15, 20, 25] total = [] # print original lists print ("list 1 : " + str(list1)) print ("list 2 : " + str(list2)) # using map() + add() to add the lists total = list(map(add, list1, list2)) # printing list print ("\nThe total Sum of Two Lists = " + str(total))
You will see the following
>>> %Run add2lists3.py list 1 : [10, 20, 30, 40, 50] list 2 : [5, 10, 15, 20, 25] The total Sum of Two Lists = [15, 30, 45, 60, 75]
Link
This is in our github repository
https://github.com/programmershelp/maxpython/tree/main/code%20example/List%20examples