Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book