Proposal: [... for ... while cond(x)]

Slawomir Nowaczyk slawomir.nowaczyk.847 at student.lu.se
Sun Aug 6 16:54:28 EDT 2006


On Sun, 06 Aug 2006 18:59:39 +0000 (GMT)
Duncan Booth <duncan.booth at invalid.invalid> wrote:

#> >> > I suggest a new extension of the list comprehension syntax:
#> >> >
#> >> > [x for x in xs while cond(x)]
#> >> >
#> >> > which would be equivalent to
#> >> >
#> >> > list(itertools.takewhile(cond, xs))
#> >>
#> >> What would this syntax offer that:
#> >>
#> >>    [x for x in takewhile(cond, xs)]
#> >>
#> >> doesn't currently offer?
#> > 
#> > The same thing that [f(x) for x in xs] offers that map(f, xs) doesn't,
#> > and the same thing that [x for x in xs if f(x)] offers that filter(f,
#> > xs) doesn't. It's more "pythonic". You can use an expression for cond
#> > instead of a lambda.
#> > 
#> No, the list comprehension lets you write an expression directly
#> avoiding a function call, and it also allows you to add in a
#> condition which can be used to filer the sequence. 

I am not sure if I understand you correctly, but... Does it?

>>> a = [0,1,2,3,7,8,9]
>>> [x for x in takewhile(lambda x: x in a, range(10))]
[0, 1, 2, 3]
>>> [x for x in takewhile(x in a, range(10))]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'bool' object is not callable

Did I miss something? Notice that using "if" gives different result:

>>> [x for x in range(10) if x in a]
[0, 1, 2, 3, 7, 8, 9]

#> Your proposal adds nothing.

Well, I am not sure how useful the proposal really is, but it seems to
add *something* if it would allow for things like:
[x for x in range(10) while x in a]

-- 
 Best wishes,
   Slawomir Nowaczyk
     ( Slawomir.Nowaczyk at cs.lth.se )

Women who seek to be equal to men lack ambition.




More information about the Python-list mailing list