A
at
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.
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.