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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With