[Tutor] flatten a python list

Peter Otten __peter__ at web.de
Mon May 31 09:11:29 EDT 2021


On 31/05/2021 05:58, Manprit Singh wrote:
> Dear sir,
> 
> consider a problem to get a flat list for below given list :
> lst = [[2, 6], [5, 8], [6, 0]]
> the flatten list will be :
> ans = [2, 6, 5, 8, 6, 0]
> 
> I have seen in several texts around the internet and even in the textbooks,
> the approach followed is to use nested for loop.
> ans = []
> for ele in lst:
>    for num in ele:
>      ans.append(num)
> 
> instead of using this for loop if i write :
> ans = []
> for ele in lst:
>    ans.extend(ele)
> 
> Although the answer is correct, I need your comments on this approach.
> 
> Just for the sake of healthy discussion, i am putting this question
> Although i can do it in a very efficient manner with list comprehension as
> given below:
> ans = [num for ele in lst for num in ele]

Here are a few other variants for your collection:

 >>> lst = [[2, 6], [5, 8], [6, 0]]
 >>> from functools import reduce
 >>> from operator import add
 >>> reduce(add, lst)
[2, 6, 5, 8, 6, 0]

This is basically add(add(lst[0], lst[1]), lst[2]) without the nesting.

You might rewrite that as lst[0] + lst[1] + lst[2], which is what sum() 
does if you provide the second argument:

 >>> sum(lst, [])
[2, 6, 5, 8, 6, 0]

reduce() is a little more flexible, you can get it to extend() a list; 
+= (or iadd) is just a different incantation of extend:

 >>> from operator import iadd
 >>> a = []
 >>> reduce(iadd, lst, a)
[2, 6, 5, 8, 6, 0]
 >>> assert a is _
 >>>

Have fun :)



More information about the Tutor mailing list