Skip to content

A Comprehensive Guide to Augmented Assignment Operators in Python

Updated: at 03:34 AM

Augmented assignment operators are a vital part of the Python programming language. These operators provide a shortcut for assigning the result of an operation back to a variable in an expressive and efficient manner.

In this comprehensive guide, we will cover the following topics related to augmented assignment operators in Python:

Table of Contents

Open Table of Contents

What Are Augmented Assignment Operators?

Augmented assignment operators are a shorthand technique that combines an arithmetic or bitwise operation with an assignment.

The augmented assignment operator performs the operation on the current value of the variable and assigns the result back to the same variable in a compact syntax.

For example:

x = 2
x += 3 # x = x + 3
print(x) # 5

Here x += 3 is equivalent to x = x + 3. The += augmented assignment operator adds the right operand 3 to the current value of x, which is 2. It then assigns the result 5 back to x.

This shorthand allows you to reduce multiple lines of code into a concise single line expression.

Some key properties of augmented assignment operators in Python:

Now let’s look at the various augmented assignment operators available in Python.

Augmented Assignment Operators List

Python supports augmented versions of all the arithmetic, bitwise, and sequence assignment operators.

Arithmetic Augmented Assignments

OperatorExampleEquivalent
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
//=x //= 3x = x // 3
%=x %= 3x = x % 3
**=x **= 3x = x ** 3

These perform the standard arithmetic operations like addition or exponentiation and assign the result back to the variable.

For example:

num = 10
num += 5 # num = num + 5
print(num) # 15

num *= 2 # num = num * 2
print(num) # 30

Bitwise Augmented Assignments

OperatorExampleEquivalent
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3

These allow you to perform bitwise AND, OR, XOR, right shift, and left shift operations combined with assignment.

For example:

bits = 0b10101010
bits &= 0b11110000 # AND assignment
print(bits) # 0b10100000

bits <<= 2 # Left shift by 2 bits
print(bits) # 0b10100000

Sequence Augmented Assignments

OperatorExampleEquivalent
+=my_list += [1, 2]my_list = my_list + [1, 2]

The += operator can also be used to concatenate sequences like lists, tuples, and strings.

For example:

fruits = ["apple"]
fruits += ["banana", "cherry"]
print(fruits) # ["apple", "banana", "cherry"]

These operators provide a shorthand for sequence concatenation.

Advantages of Augmented Assignment Operators

Some key advantages of using augmented assignment operators:

For these reasons, augmented assignments should be preferred over explicit expansion into longer compound statements in most cases.

Some examples of effective usage:

So whenever you need to assign the result of some operation back into a variable, consider using the augmented version.

Common Mistakes to Avoid

While augmented assignment operators are very handy, some common mistakes can occur:

Augmented Assignment with Mutable Types

Augmented assignments act inplace and modify the existing object. This can be problematic with mutable types like lists:

values = [1, 2]
values += [3, 4] # Modifies existing list
print(values) # [1, 2, 3, 4]

In contrast, normal operators with immutable types create a new object:

values = [1, 2]
values = values + [3, 4] # Creates new list
print(values) # [1, 2, 3, 4]

So be careful when using augmented assignments with mutable types, as they modify the object in-place rather than creating a new object.

Operator Precedence and Order of Evaluation

Augmented assignment operators have right-associativity. This can cause unexpected results:

x = y = 0
x += y += 1 # Equivalent to x += (y += 1)
print(x, y) # 1 1

The right-most operation y += 1 is evaluated first updating y. Then x += y uses the new value of y.

To avoid this, use parenthesis to control order of evaluation:

x = y = 0
y += 1
x += y
print(x, y) # 1 1

Updating Multiple References

When you augmented assign to a variable, it updates all references to that object:

x = [1, 2]
y = x
x += [3]

print(x) # [1, 2, 3]
print(y) # [1, 2, 3]

y also reflects the change since it points to the same mutable list as x.

To avoid this, reassign the variable rather than using augmented assignment:

x = [1, 2]
y = x[:] # Copy x
x = x + [3] # Reassign x

print(x) # [1, 2, 3]
print(y) # [1, 2]

Augmented Assignment vs Normal Assignment

While the augmented assignment operators provide a shorthand, they differ from standard assignment in some key ways:

In summary, augmented assignment operators combine both an operation and assignment but evaluate differently than standard operators.

Comparisons to Other Languages

Augmented assignments exist in many other languages like C/C++, Java, JavaScript, Go, Rust, etc. Some key differences to Python:

So while augmented assignment is common across languages, Python provides some unique behaviors to be aware of.

Best Practices and Style Guide

Here are some best practices when using augmented assignments in Python:

Following PEP 8 style, augmented assignments should have the same spacing and syntax as normal assignment operators. Just be mindful of potential pitfalls.

Conclusion

Augmented assignment operators provide a compact yet expressive shorthand for modifying variables in Python. They combine an operation and assignment into one atomic expression.

Key takeaways:

I hope this guide gives you a comprehensive understanding of augmented assignment in Python. Use these operators appropriately to write clean, idiomatic Python code.