user2058002
user2058002

Reputation:

Summing two lists together

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

Answers (3)

Pratik Singhal
Pratik Singhal

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

Waterlink
Waterlink

Reputation: 2369

sum will do following:

  1. initialize result = 0
  2. for each element in input list: result += element
  3. return result

So 2nd step will yield such error. You trying to do result += element, where result = 0 and element = [1, 2]. This should yield TypeError.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798656

start defaults to 0.

source

sum(..., [])

Upvotes: 6

Related Questions