Reputation:
Observing that [1, 2] + [3, 4]
yielded [1, 2, 3, 4]
, I reasoned that sum([[1, 2], [3, 4]])
should do the same, but instead I got this error:
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Can someone please explain this? I know I can use itertools.chain
, but why doesn't this work?
Upvotes: 0
Views: 125
Reputation: 6492
Sume works like this
sum([[1,2], [3,4]])
As you can see in the documentation of sum function , sum works by adding each new element to the previously held value. In this case you are trying to add [3,4] + 1 which will lead to the error as adding list and int doesn't make sense.
Upvotes: -1