Python | In-Place Operators

In-place operators allow you to write code like x = x + 3 more concisely, as x += 3. The same thing is possible with other operators such as -, *, / and % as well.

x = 3
print(x)
x += 5
print(x)

The output in the terminal will be:

>>>> x = 3
>>> print(x)
3
>>> x += 5
>>> print(x)
8
>>>

These operators can be used on types other than numbers, such as strings.

x = “mobile”
print(x)
x += “phone”
print(x)

The output in the terminal will be:

>>> x = "mobile"
>>> print(x)
mobile
>>> x += "phone"
>>> print(x)
mobilephone
>>> 

Many other languages have special operators such as ++ as a shortcut for x += 1 (JavaScript). Python does not have these.

Leave a Reply