Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>flat_list = [item for sublist in l for item in sublist] </code></pre> <p>which means:</p> <pre><code>for sublist in l: for item in sublist: flat_list.append(item) </code></pre> <p>is faster than the shortcuts posted so far. (<code>l</code> is the list to flatten.)</p> <p>Here is a the corresponding function:</p> <pre><code>flatten = lambda l: [item for sublist in l for item in sublist] </code></pre> <p>For evidence, as always, you can use the <code>timeit</code> module in the standard library:</p> <pre><code>$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 10000 loops, best of 3: 143 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])' 1000 loops, best of 3: 969 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)' 1000 loops, best of 3: 1.1 msec per loop </code></pre> <p>Explanation: the shortcuts based on <code>+</code> (including the implied use in <code>sum</code>) are, of necessity, <code>O(L**2)</code> when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So (for simplicity and without actual loss of generality) say you have L sublists of I items each: the first I items are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the sum of x for x from 1 to L excluded, i.e., <code>I * (L**2)/2</code>.</p> <p>The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.</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