[Tutor] flatten a python list

Alan Gauld alan.gauld at yahoo.co.uk
Mon May 31 05:15:44 EDT 2021


On 31/05/2021 04:58, Manprit Singh wrote:

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

Both are valid.

Both are flawed if the lists are not homogenous.
For example if lst contained single numbers as
well as sub lists. Or if the sublists can contain
sub lists of their own. To flatten a list in the
real world you'd probably want some type checking
and possibly use a recursive function to process
multiple layers of sublists..

> ans = [num for ele in lst for num in ele]

This also works but loses a lot in readability.
Unless it was proven to be much faster and
that speed was actually needed I'd stick
with either of the more explicit versions above.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list