Reputation: 430
a = sum([[1, 4], [2, 3]],[])
#output = [1, 4, 2, 3]
Can please explain how does the start = [] unpack both list? Thanks
Upvotes: 0
Views: 39
Reputation: 6866
sum()
adds all elements in the input collection, as if they were joined by the +
operator. One possible implementation could be something like this:
def sum(vals, start=0):
result = start
for v in vals:
result = result + v
return result
Since the default start value is 0
, and int + list
gives a type error, supplying []
as the start value instead will give the expected result.
In the end, a = sum([[1, 4], [2, 3]],[])
will behave equivalently to:
a = []
a = a + [1, 4]
a = a + [2, 3]
Upvotes: 3