Augmented Assignment
Python provides the following set of augmented assignment operators:
Operation |
Description |
x += y |
x = x + y |
x -= y |
x = x - y |
x *= y |
x = x * y |
x /= y |
x = x / y |
x //= y |
x = x // y |
x **= y |
x = x ** y |
x %= y |
x = x % y |
x &= y |
x = x & y |
x |= y |
x = x | y |
x ^= y |
x = x ^ y |
x >>= y |
x = x >> y |
x <<= y |
x = x << y |
These operators can be used anywhere that ordinary assignment is used. For example:
a = 3 b = [1,2] c = "Hello %s %s" a += 1 # a = 4 b[1] += 10 # b = [1, 12] c %= ("Monty", "Python") # c = "Hello Monty Python"
Augmented assignment doesn't violate mutability or perform in-place modification of objects. Therefore, writing x += y creates an entirely new object x with the value x + y. User-defined classes can redefine the augmented assignment operators using the special methods described in Chapter 3, "Types and Objects."