do you master list comprehensions?

Fredrik Lundh fredrik at pythonware.com
Tue Dec 14 18:41:23 CET 2004


Steven Bethard wrote:

> > python -m timeit -s "data = [range(10) for _ in range(1000)]"
> "sum(data, [])"
> 10 loops, best of 3: 54.2 msec per loop
>
> > python -m timeit -s "data = [range(10) for _ in range(1000)]" "[w for
> d in data for w in d]"
> 100 loops, best of 3: 1.75 msec per loop
>
> The sum function used in this way (or a loop with a +=) is O(N**2) while the LC is O(N).

also:

timeit -s "data = [range(10) for _ in range(1000)]" "L = sum(data, [])"
10 loops, best of 3: 4.02e+004 usec per loop

timeit -s "data = [range(10) for _ in range(1000)]" "L = [w for d in data for w in d]"
1000 loops, best of 3: 1.12e+003 usec per loop

timeit -s "data = [range(10) for _ in range(1000)]" "L = []; map(L.extend, data)"
1000 loops, best of 3: 283 usec per loop

timeit -s "data = [range(10) for _ in range(1000)]; from Tkinter import _flatten" "L = 
_flatten(data)"
1000 loops, best of 3: 308 usec per loop

(the last one supports arbitrary nestings, the others don't)

</F> 






More information about the Python-list mailing list