How to create a new list by adding elements from multiple lists of same length in python ?

Active December 17, 2020    /    Viewed 2563    /    Comments 0    /    Edit


An example of how to sum elements from multiple lists of same size in python:

Lists of same length

Let's define for example 3 lists of same size in python:

a = [1,2,3,4]

b = [10,20,30,40]

c = [1,1,1,1]

Sum elements from multiple lists to create a new list

To create a new list by adding the element by adding elements from multiple lists, a solution is to use a list comprehension and zip:

d = [x+y+z for x, y, z in zip(a, b, c)]

print(d)

returns

[12, 23, 34, 45]

Sum all elements

Note: to add all elements together just use sum():

tot = sum(d)

print(tot)

returns

114


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount