conditional for-statement

Chris Rebert clp2 at rebertia.com
Sun Aug 23 17:02:16 EDT 2009


On Sun, Aug 23, 2009 at 1:36 PM, seb<sdementen at gmail.com> wrote:
> On Aug 23, 6:18 pm, John Posner <jjpos... at optimum.net> wrote:
>> >> Hi,
>>
>> >> i was wondering if there is a syntax alike:
>>
>> >> for i in range(10) if i > 5:
>> >>     print i
>>
>> > You can write
>>
>> > for i in filter(lambda i: i > 5, range(10)):
>> >     print i
>>
>> > but
>>
>> > for i in range(10):
>> >     if i > 5:
>> >         print i
>>
>> > it' better readable, and
>>
>> > for i in range(6,10):
>> >     print i
>>
>> > it's event better.
>>
>> How about using a generator expression instead of a list?
>>
>>   for i in (x for x in range(10) if x > 5):
>>       print i
>>
>> -John
>
> Indeed, but we could have the same syntax than for generators but
> directly in the for statement as in
> for variable in generator if condition:
>    body
>
> Is there a special reason for not doing so ? A rejected PEP ?

It's not been added since it's completely unnecessary (see the several
alternatives already presented by others).
There have been a few other mailinglist threads on adding essentially
the same syntax. None have proved fruitful.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list