O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Augmented Assignment

Python provides the following set of augmented assignment operators:

OperationDescription
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x //= yx = x // y
x **= yx = x ** y
x %= yx = x % y
x &= yx = x & y
x |= yx = x | y
x ^= yx = x ^ y
x >>= yx = x >> y
x <<= yx = 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required