Linux/Unix > Python Essential Reference, Second Edition > 4. Operators and Expressions > Augmented Assignment | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104030195076075218197060

### 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 classes can redefine the augmented assignment operators using the special methods described in Chapter 3, “Types and Objects.”

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.