'The operations for sum([[3], [5]], [])

This is a very simple expression, but I have no idea how it operates.

print(sum([[3], [5]], []))

# returns [3,5] 

why on earth does sum([[3], [5]], []) return [3,5]? My knowledge on sum() is that it takes in an iterable and sums the elements in the iterable. So usually the elements are integers. For example, I'm familiar with something like:

sum([1,2,3])

# returns 6 

But sum([[3], [5]], []) has two inputs, one a list of lists, and another an empty list. I thought this would return an error, but surprisingly it returned the above result. I haven't seen something like this before, and I would appreciate it if anyone could tell me the operations going on for this example.



Solution 1:[1]

sum() takes two parameters :

  • the iterable (here [[3],[5]])
  • the start, which has a default value of 0 (an int)

When you use

sum([[3],[5]])

start has the default value 0, so the function tries to add [3] and [5] to 0, an int, so you have TypeError.

On the other hand, when you use

sum([[3],[5]],[])

with [] as start value, [] + [3] + [5], it first instantiates an empty list before adding list-type elements to it.

This sum is correct with output [3,5]

Solution 2:[2]

This is equivalent to:

s = []
for lst in [[3], [5]]:
    s += lst

You need to know that the list can be connected through the operator +?even if it contains an empty list, it will get a copy of another list.

About why sum ([[3], [5]]) raise error, see the signature of sum function:

sum(iterable, start)

If you don't specify start, the default value seems to be 0, which of course cannot be added to the list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sören