Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add the corresponding elements of several lists of numbers?

Tags:

python

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?

like image 425
kuafu Avatar asked Jul 01 '12 08:07

kuafu


People also ask

How do you sum elements in a list?

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.

How do you add elements to two lists?

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.

How do you sum a list of numbers 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.

Which function of list can add multiple elements given in the form of a list to a list?

extend() extend() can add multiple items to a list.


1 Answers

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:

  • Getting a map() to return a list in Python 3.x

(You can just call list).

like image 106
Mark Byers Avatar answered Oct 08 '22 02:10

Mark Byers