[Tutor] List comprehension for dicts?

bob gailer bgailer at gmail.com
Fri Aug 20 17:47:12 CEST 2010


  On 8/20/2010 5:44 AM, Steven D'Aprano wrote:
> 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.
>
Take a look at itertools.takewhile!

result = [i%2 for i in itertools.takewhile(lamda x:i<  10, seq)]


-- 
Bob Gailer
919-636-4239
Chapel Hill NC



More information about the Tutor mailing list