a break for comprehensions

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Thu Jul 26 11:42:26 EDT 2001


Thu, 26 Jul 2001 10:44:55 -0400, Kevin Lacker <kdl4 at acpub.duke.edu> pisze:

> 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?

The pattern can be wrapped in a function. It's quite nice in Python 2.2:

def take_while(p, l):
    for x in l:
        if not p(x): break
        yield x

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

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

Looks nice for me.

-- 
 __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
 \__/
  ^^                      SYGNATURA ZASTĘPCZA
QRCZAK



More information about the Python-list mailing list