This is an archived version of the course. Please see the latest version of the course.

Assignment operator

In Python, you can assign the same object to multiple variables at once.

>>> x = y = 558
>>> print(x)
>>> print(y)

You can also perform multiple assignments simultaneously.

>>> x, y, z = 5, 5, 8
>>> print(x)
>>> print(y)
>>> print(z)

This naturally allows you to easily swap the values of variables, without requiring an intermediate variable.

>>> x = 5
>>> y = 8
>>> x, y = y, x
>>> print(x)
>>> print(y)

“Shortcut” assignment operators

You can also use these “shortcut” assignment operators just like in C++: +=, -=, *=, /=, %=, //=, **=

x += y is equivalent to x = x + y.

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.