Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you consider to be the best way to flatten a shallow list like this, balancing performance and readability?

I tried to flatten such a list with a nested list comprehension, like this:

[image for image in menuitem for menuitem in list_of_menuitems]

But I get in trouble of the NameError variety there, because the name 'menuitem' is not defined. After googling and looking around on Stack Overflow, I got the desired results with a reduced statement:

reduce(list.__add__, map(lambda x:

list(x), list_of_menuitems))

But this method is fairly unreadable because I need that list(x) call there because x is a Django QuerySet object.

1 Answer

0 votes
by (106k points)

For Flattening a shallow list in Python you can use the nested list comprehensions it is used to put the for statements in the same order as they would go in regular nested for statements.

for inner_list in outer_list:

   for item in inner_list:


Below is the syntax for flatten a list what you were trying to do :

[... for inner_list in outer_list for item in inner_list]

And this is the proper code that you were doing:-

[image for menuitem in list_of_menuitems for image in menuitem]

Browse Categories