[Tutor] List comprehension for dicts?

Steven D'Aprano steve at pearwood.info
Sat Aug 21 03:51:24 CEST 2010


On Sat, 21 Aug 2010 01:47:12 am bob gailer wrote:

> > 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)]

Which is an excellent solution to the problem, and I had forgotten about 
it, but takewhile doesn't magically cause the list comprehension to 
exit. The list comp still runs over the entire input list, it's just 
that it sees a smaller input list.

takewhile replaces the input sequence with a new sequence that stops at 
a certain point, so you could write:

result = []
for i in itertools.takewhile(lambda x:i<10, seq):
    result.append(i)

as well.

Next time some Perl hacker accuses Python of being "Only one way to do 
it", you can just laugh at them :)



-- 
Steven D'Aprano


More information about the Tutor mailing list