Python for Java Programmers
Chapter 3: Variables and operators
Assignment operator
In Python, you can assign the same object to multiple variables at once.
>>> x = y = 395
>>> print(x)
>>> print(y)
You can also perform multiple assignments simultaneously.
>>> x, y, z = 3, 9, 5
>>> print(x)
>>> print(y)
>>> print(z)
This naturally allows you to easily swap the values of variables, without requiring an intermediate variable. It’s actually the recommended way to swap variables in Python!
>>> x = 3
>>> y = 9
>>> x, y = y, x
>>> print(x)
>>> print(y)
‘Shortcut’ assignment operators
You can also use these ‘shortcut’ assignment operators just like in Java: +=, -=, *=, /=, %=, //=, **=.
x += y is equivalent to x = x + y.
Formally, these are called augmented assignments.
You CANNOT do x++ and --y in Python. Sorry! Remember one of the philosophies behind Python – there should preferably be only one (obvious) way to do something.