Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're just looking to iterate over a flattened version of the data structure and don't need an indexable sequence, consider <a href="http://docs.python.org/library/itertools.html#itertools.chain" rel="noreferrer">itertools.chain and company</a>.</p> <pre><code>&gt;&gt;&gt; list_of_menuitems = [['image00', 'image01'], ['image10'], []] &gt;&gt;&gt; import itertools &gt;&gt;&gt; chain = itertools.chain(*list_of_menuitems) &gt;&gt;&gt; print(list(chain)) ['image00', 'image01', 'image10'] </code></pre> <p>It will work on anything that's iterable, which should include Django's iterable <code>QuerySet</code>s, which it appears that you're using in the question.</p> <p><strong>Edit:</strong> This is probably as good as a reduce anyway, because reduce will have the same overhead copying the items into the list that's being extended. <code>chain</code> will only incur this (same) overhead if you run <code>list(chain)</code> at the end.</p> <p><strong>Meta-Edit:</strong> Actually, it's less overhead than the question's proposed solution, because you throw away the temporary lists you create when you extend the original with the temporary.</p> <p><strong>Edit:</strong> As <a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python#411548">J.F. Sebastian says</a> <code>itertools.chain.from_iterable</code> avoids the unpacking and you should use that to avoid <code>*</code> magic, but <a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python#408281">the timeit app</a> shows negligible performance difference.</p>
 

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