@Jon Clements gave you a great answer: how to solve a problem using the Python idiom. If other Python programmers look at its code, they will immediately understand it. This is just the right way to do this using Python.
To answer your real question: no, this does not work. The ternary operator has the following form:
expr1 if condition else expr2
condition should be something that evaluates to bool . The triple expression selects one of expr1 and expr2 and that is it.
When I tried an expression like c += 1 if condition else 0 , I was surprised that it worked, and noted that in the first version of this answer. @TokenMacGuy noted that the following is actually happening:
c += (1 if condition else 0)
That way, you can never do what you are trying to do, even if you put the right condition in place of some kind of loop. The above case will work, but something like this will fail:
c += 1 if condition else x += 2 # syntax error on x += 2
This is because Python does not consider the assignment operator to be an expression.
You cannot make this common mistake:
if x = 3: # syntax error! Cannot put assignment statement here print("x: {}".format(x))
Here, the programmer most likely wanted x == 3 to check the value, but typed x = 3 . Python protects this error, not counting the assignment to an expression.
You cannot do this by mistake, and you cannot do this either.
steveha
source share