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?
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]
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]
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