Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing non-integers in Python

Tags:

python

sum

Is it possible to take the sum of non-integers in Python?

I tried the command

sum([[1], [2]])

to get [1, 2], but it gives the error

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    sum([[1], [2]])
TypeError: unsupported operand type(s) for +: 'int' and 'list'

I suspect sum tries to add 0 to the list [1], resulting in failure. I'm sure there are many hacks to work around this limitation (wrapping stuff in a class, and implementing __radd__ manually), but is there a more elegant way to do this?

like image 261
doug Avatar asked Nov 27 '22 15:11

doug


2 Answers

It looks like you want this:

>>> sum([[1],[2]], [])
[1, 2]

You're right that it's trying to add 0 to [1] and getting an error. The solution is to give sum an extra parameter giving the start value, which for you would be the empty list.

Edit: As gnibbler says, though, sum is not a good way to concatenate things. And if you just want to aggregate a sequence of things, you should probably use reduce rather than make your own __radd__ function just to use sum. Here's an example (with the same poor behavior as sum):

>>> reduce(lambda x, y: x+y, [[1],[2]])
[1, 2]
like image 145
Gabe Avatar answered Nov 30 '22 03:11

Gabe


It's a bad idea to use sum() on anything other than numbers, as it has quadradic performance for sequences/strings/etc.

Better to use a list comprehension to sum your lists

[j for i in [[1],[2]] for j in i]
like image 20
John La Rooy Avatar answered Nov 30 '22 05:11

John La Rooy