Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing over lists in python - is there a better way?

Tags:

python

list

sum

Is there a more sensible way of doing this? I want to make a new list by summing over the indices of a lot of other lists. I'm fairly new to programming and this seems like a very clunky method!

list1 = [1,2,3,4,5]
list2 = [1,1,1,4,1]
list3 = [1,22,3,1,5]
list4 = [1,2,5,4,5]
...
list100 = [4,5,6,7,8]

i = 0
while i < len(list1):
    mynewlist[i] = list1[i]+list2[i]+list3[i]+list4[i]+...list100[i]
    i = i+1
like image 411
FakeDIY Avatar asked May 23 '12 15:05

FakeDIY


People also ask

Is there a sum function for lists in Python?

sum() function in Python Sum of numbers in the list is required everywhere. 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.

Is sum faster than for loop Python?

Why is that? How is sum implemented? sum is implemented in C inside the Python interpreter, while your for loop has to be interpreted, it's normal that it's slower. In CPython built-in functions are much faster than the pure-python translation.

Can you sum two lists in Python?

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.


1 Answers

This is a pretty good use case for zip.

>>> list1 = [1,2,3,4,5]
>>> list2 = [1,1,1,4,1]
>>> list3 = [1,22,3,1,5]
>>> list4 = [1,2,5,4,5]
>>> [sum(x) for x in zip(list1, list2, list3, list4)]
[4, 27, 12, 13, 16]

or if you have your data as a list of lists instead of separate lists:

>>> data = [[1,2,3,4,5], [1,1,1,4,1], [1,22,3,1,5], [1,2,5,4,5]]
>>> [sum(x) for x in zip(*data)]
[4, 27, 12, 13, 16]

similarly, if you store your data as a dict of lists, you can use dict.itervalues() or dict.values() to retrieve the list values and use that in a similar fashion:

>>> data = {"a":[1,2,3], "b":[3,4,4]}
>>> [sum(x) for x in zip(*data.itervalues())]
[4, 6, 7]

Note that if your lists are of unequal length, zip will work up till the shortest list length. For example:

>>> data = [[1,2,3,4,5], [1,1], [1,22], [1,2,5]]
>>> [sum(x) for x in zip(*data)]
[4, 27]

If you wish to get a result that includes all data, you can use itertools.izip_longest (with an appropriate fillvalue). Example:

>>> data = [[1,2,3,4,5], [1,1], [1,22], [1,2,5]]
>>> [sum(x) for x in izip_longest(*data, fillvalue=0)]
[4, 27, 8, 4, 5]
like image 83
Shawn Chin Avatar answered Oct 04 '22 03:10

Shawn Chin