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 _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor