[Tutor] List comprehension for dicts?

Alan Gauld alan.gauld at btinternet.com
Fri Aug 20 10:10:59 CEST 2010


"Steven D'Aprano" <steve at pearwood.info> wrote

> the purpose). No matter how fast you can perform a loop, it's always
> faster to avoid it altogether, so this:
>
> seq = xrange(10000000)
> result = []
> for i in seq:
>    if i >= 10: break
>    result.append(i%2)
>
>
> will be much faster than this:
>
> seq = xrange(10000000)
> result = [i%2 for i in seq if i < 10]

Although it should be pointed out that these are doing very different 
things.
The equivalent loop would use continue rather than break, in which
case the LC might be faster. But where you do only want to partially
process a list the explicit loop is the best solution for now.

<Wish>
I've always wanted an until clause in the LC structure:

result = [i%2 for i in seq until i>10]
</wish>


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list