Conditional iteration

shandy.b at gmail.com shandy.b at gmail.com
Wed Dec 13 14:10:38 EST 2006


The proposed solution impairs readability because there's a "surprise"
at the end.  List comprehensions already open the language up to
readability abuse.  Lets not add more.

To avoid the unwanted indentation, I would go with the already
suggested "if not x>0: continue" solution or else something like this:

positiveMembers = [x for x in [-2, -1, 0, 1, 2, 3, 4] if x>0]
for x in positiveMembers:
    #do stuff

This has the advantage of being more self-documenting.

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