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

These operators can be used anywhere that ordinary assignment is used. For example:

a = 3 
b = [1,2] 
c = "%s %s" 
a += 1                      # a = 4 
b[1] += 10                  # b = [1, 12] 
c %= ("Douglas", "Adams")    # c = "Douglas Adams" 

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 ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.