Note that there are some explanatory texts on larger screens.

plurals
  1. POFlattening a shallow list in Python
    text
    copied!<p>Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you all consider to be the best way to flatten a shallow list like this, balancing performance and readability?</p> <p>I tried to flatten such a list with a nested list comprehension, like this:</p> <pre><code>[image for image in menuitem for menuitem in list_of_menuitems] </code></pre> <p>But I get in trouble of the <code>NameError</code> variety there, because the <code>name 'menuitem' is not defined</code>. After googling and looking around on Stack Overflow, I got the desired results with a <code>reduce</code> statement:</p> <pre><code>reduce(list.__add__, map(lambda x: list(x), list_of_menuitems)) </code></pre> <p>But this method is fairly unreadable because I need that <code>list(x)</code> call there because x is a Django <code>QuerySet</code> object.</p> <p><strong>Conclusion</strong>: </p> <p>Thanks to everyone who contributed to this question. Here is a summary of what I learned. I'm also making this a community wiki in case others want to add to or correct these observations.</p> <p>My original reduce statement is redundant and is better written this way:</p> <pre><code>&gt;&gt;&gt; reduce(list.__add__, (list(mi) for mi in list_of_menuitems)) </code></pre> <p>This is the correct syntax for a nested list comprehension (Brilliant summary <a href="https://stackoverflow.com/users/3002/df">dF</a>!):</p> <pre><code>&gt;&gt;&gt; [image for mi in list_of_menuitems for image in mi] </code></pre> <p>But neither of these methods are as efficient as using <code>itertools.chain</code>:</p> <pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; list(chain(*list_of_menuitems)) </code></pre> <p>And as @cdleary notes, it's probably better style to avoid * operator magic by using <code>chain.from_iterable</code> like so:</p> <pre><code>&gt;&gt;&gt; chain = itertools.chain.from_iterable([[1,2],[3],[5,89],[],[6]]) &gt;&gt;&gt; print(list(chain)) &gt;&gt;&gt; [1, 2, 3, 5, 89, 6] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload