Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "sum" of a list in python flatten it? [duplicate]

I have recently discovered an interesting feature in python

If you type:

y=[[1,2],[3,4]]
sum(y,[])

Output is: [1, 2, 3, 4]

Does anyone know why the sum of a series of lists with an empty list gives a flattened version of y (i.e: all of the sub-lists of y as a single list)?

I would have expected the output to be a concatenation: [1,2],[3,4],[]

Thanks

like image 907
EML Avatar asked Mar 04 '23 20:03

EML


1 Answers

sum iterates through an iterable and adds each element. It just so happens that with lists, addition is defined to be concatenation. By setting the second parameter (start) to [], the function begins with a list and keeps adding on elements to it. Effectively:

sum([[1, 2], [3, 4]], []) == [] + [1, 2] + [3, 4]
like image 181
TrebledJ Avatar answered Mar 13 '23 05:03

TrebledJ