a break for comprehensions

Kevin Lacker kdl4 at acpub.duke.edu
Thu Jul 26 10:44:55 EDT 2001


Can you do this:

answer = []
for x in my_list:
    if not is_good(x):
        break
    answer.append(process(x))

with a list comprehension somehow? I'm starting to dislike explicit for
loops just for the purposes of constructing another list from a current one.

Would this work in the future python with iterators...

def done(): raise StopIteration
answer = [process(x) for x in my_list if is_good(x) or done()]

If I used it a lot it might not be a pain to define done(). I think it would
be cool to be able to reuse the while keyword inside comprehensions like

answer = [process(x) for x in my_list while is_good(x)]

Makes sense to me... it's like being able to use a sentinel with iterators
but more flexible.





More information about the Python-list mailing list