[Tutor] flatten a python list

Cameron Simpson cs at cskk.id.au
Mon May 31 01:11:32 EDT 2021


On 31May2021 09:28, Manprit Singh <manpritsinghece at gmail.com> wrote:
>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)

That is a direct solution.

>instead of using this for loop if i write :
>ans = []
>for ele in lst:
>  ans.extend(ele)

I would expect this to be faster because the target list gets to 
allocate new slots in batches of the size of "ele". Rather than 
accomodating new elements one at a time. With small lists the like your 
example the different might be small. With large lists (each ele" being 
long) it might be more obvious.

>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]

This is concise. Is it more efficient than the nested for-loops 
appending a single element?

Check out the timeit module, which is useful for benchmarking things 
like this (timing very small operations such as your example is 
unreliable because the run time is so small - timeit runs the task many 
times).

Note: the difference between the two may be small. Even when the "ele" 
sublists are very large the internals of the "list" type might be good 
enough to make the difference small.

Often, unless this is a performance bottleneck, you should go with the 
most readable/understandable solution.

Finally: in the case where large "ele" makes a big difference, you might 
be better of _not_ flattening the list at all - it can be expensive.  
instead your use case might one need to _use_ the elements in flattened 
form without the step of constructing a distinct new list.

See the "chain" function in the itertools module.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list