Conditional iteration

mystilleef mystilleef at gmail.com
Fri Dec 15 04:51:35 EST 2006


This why I prefer functional programming constructs for my
list/sequence processing needs.

------------------------------------------------------------------------
is_true = lambda x: x > 0
map(process_list, filter(is_true, [-2, -1, 0, 1, 2, 3, 4]))
------------------------------------------------------------------------

at wrote:
> I would like to spark the discussion about the following syntax problem I
> encounter.
>
> THE PROBLEM
>
> I have a lot times the following code:
>
> for x in [-2, -1, 0, 1, 2, 3, 4]:
>         if x > 0:
>                 ... more code...
>
>
> It is not the addional line containing 'if x > 0:' that bothers me, but the
> additional indentation.
>
>
> THE SOLUTION
>
> More pythonic in view would be:
>
> for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0:
>         ... more code ...
>
>
> This blends basically
>
>         [x for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0]
>
> and
>
>         x = y if x > 0 else 10
>
>
> EXTENDING
>
> And maybe a few usefull variants, like:
>
> for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0 else -x:
>         ... more code ...
> 
> In this case x will be 2, 1, 0, 1, 2, 3, 4.




More information about the Python-list mailing list