I have some lists of numbers:
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
How can I add these lists' elements, assuming that all of the lists that I'm using are the same length?
Here's the kind of output I'd like to get from doing this to the above lists.
[6, 9, 12, 15, 18]
I know that I'll need a loop of some kind - but how can I do it elegantly?
Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.
The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists. Let's consider a program to add the list elements using the zip function and sum function in Python.
sum() function in Python Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.
extend() extend() can add multiple items to a list.
Try this functional style code:
>>> map(sum, zip(*lists))
[6, 9, 12, 15, 18]
The zip
function matches elements with the same index.
>>> zip(*lists)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
Then sum
is applied to each tuple by using map
.
See it working online: ideone
Note that in Python 3.x, map
no longer returns a list. If you need the list, please see the following question:
(You can just call list
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With