[Tutor] List comprehension for dicts?
Steven D'Aprano
steve at pearwood.info
Fri Aug 20 11:44:38 CEST 2010
On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote:
> "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.
Well yes, but I pointed out that you *can* bail out early of for-loops,
but not list comprehensions. The whole point is with a list comp,
you're forced to iterate over the entire sequence, even if you know
that you're done and would like to exit.
--
Steven D'Aprano
More information about the Tutor
mailing list