Skip to content Skip to sidebar Skip to footer

Chaining *= += Operators

I have the following code: aaa = np.random.rand(20, 1) aaa *= 200 aaa -= 100 I wonder if it is possible to chain *= and -= operators on the same line. So, the loop over the array

Solution 1:

You cannot chain assignments in Python the way you can in C.

That is because in C an assignment is an expression: it has a value that can be assigned to a variable, or used in another expression. C got this idea from Algol, and those who come from the Pascal tradition tend to regard it as a misfeature. Because...

It is a trap for unwary novices who code if (a = b + c) when they mean if (a == b + c). Both are valid, but generally the second one is what you meant, because the first assigns the value of b + c to a and then tests the truth value of a.

Because assignments are not expressions in Python but statements, you will get a syntax error for if (a = b + c). It's just as invalid as if (return).

If you want to achieve what the C idiom does you can use an assignment expression (new in 3.8). You can explicitly code if (a := b + c) if what you really want to do is assign the value of b + c to a and then test the truth value of a (though technically I believe it actually tests the truth value of b + c; which comes to the same thing).

[And to the style martinets, yes, I do know that parens are redundant in a Python if statement.]


Solution 2:

Doing them in one line would simply be

aaa = (aaa * 200) - 100

Though I doubt you'll see any performance difference between this version and what you wrote.


Post a Comment for "Chaining *= += Operators"