When I want to unfold a list, I found a way like below:
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> a
[[1, 2], [3, 4], [5, 6]]
>>> sum(a,
First of all, never use sum
for concatenating/flattening lists because it's of quadratic time and hence not efficient at all compare to the other ways around. It actually uses a schlemiel the painter algorithm.
The sum
function calls the __add__
attribute of the start
on each iteration with all the items of an iterable that's been passed as the first argument.
For example :
>>> [].__add__([2,3])
[2, 3]
#OR
>>> [] + [1,2,3]
[1, 2, 3]
And in this case the result would be a concatenated list of your input lists. From an algorithmic perspective it does the followings:
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> start = []
>>> for i in a:
... start += i
...
>>> start
[1, 2, 3, 4, 5, 6]
Not that you can call the sum
function on any sequence of objects that have an __add__
attribute, but note that since the default start
argument is 0
if your object is not an integer it will raise an TypeError
. In that case you need to specify a proper start
for the function.
>>> class newObj(object):
... def __init__(self,val):
... self.val = val
... def __add__(self,item):
... return '{}_____{}'.format(self.val,item)
...
>>>
>>> start=newObj('new_obj')
>>>
>>> start
<__main__.newObj object at 0x7f75f9241c50>
>>>
>>> start + 5
'new_obj_____5'
>>>
>>>
>>> sum(['1','2','3'],start)
'new_obj_____123'