Proposal: [... for ... while cond(x)]
Duncan Booth
duncan.booth at invalid.invalid
Sun Aug 6 14:59:39 EDT 2006
Eighty wrote:
>
> Duncan Booth wrote:
>> Eighty 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? (Apart, that is, from saving you 3
>> characters of typing)
>
> 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. Your proposal adds nothing.
More information about the Python-list
mailing list