conditional for-statement

John Posner jjposner at optimum.net
Sun Aug 23 18:18:43 CEST 2009


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



More information about the Python-list mailing list