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:
- Operators act inplace directly modifying the variable’s value
- Work on mutable types like lists, sets, dicts unlike normal operators
- Generally have equivalent compound statement forms using standard operators
- Have right-associative evaluation order unlike arithmetic operators
- Available for arithmetic, bitwise, and sequence operations
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
Operator | Example | Equivalent |
---|---|---|
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
//= | x //= 3 | x = x // 3 |
%= | x %= 3 | x = x % 3 |
**= | x **= 3 | x = 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
Operator | Example | Equivalent |
---|---|---|
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = 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
Operator | Example | Equivalent |
---|---|---|
+= | 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:
-
Conciseness: Performs an operation and assignment in one concise expression rather than multiple lines or steps.
-
Readability: The operator itself makes the code’s intention very clear.
x += 3
is more readable thanx = x + 3
. -
Efficiency: Saves executing multiple operations and creates less intermediate objects compared to chaining or sequencing the operations. The variable is modified in-place.
For these reasons, augmented assignments should be preferred over explicit expansion into longer compound statements in most cases.
Some examples of effective usage:
- Incrementing/decrementing variables:
index += 1
- Accumulating sums:
total += price
- Appending to sequences:
names += ["Sarah", "John"]
- Bit masking tasks:
bits |= 0b100
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:
-
Inplace modification: Augmented assignment acts inplace and modifies the existing variable rather than creating a new object.
-
Mutable types: Works directly on mutable types like lists, sets, and dicts unlike normal assignment.
-
Order of evaluation: Has right-associativity unlike left-associativity of normal assignment.
-
Multiple references: Affects all references to a mutable object unlike normal assignment.
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:
-
In C/C++ augmented assignments return the assigned value allowing usage in expressions unlike Python which returns
None
. -
Java and JavaScript don’t allow augmented assignment with strings unlike Python which supports
+=
for concatenation. -
Go doesn’t have an increment/decrement operator like
++
and--
. Python’s+= 1
and-= 1
serves a similar purpose. -
Rust doesn’t allow built-in types like integers to be reassigned with augmented assignment and requires mutable variables be defined with
mut
.
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:
-
Use whitespace around the operators:
x += 1
rather thanx+=1
for readability. -
Limit chaining augmented assignments like
x = y = 0
. Use temporary variables if needed for clarity. -
Don’t overuse augmented assignment especially with mutable types. Reassignment may be better if the original object shouldn’t be changed.
-
Watch the order of evaluation with multiple augmented assignments on one line due to right-associativity.
-
Consider parentheses for explicit order of evaluation:
x += (y + z)
rather than relying on precedence. -
For increments/decrements, prefer
+= 1
and-= 1
rather thanx = x + 1
andx = x - 1
. -
Use normal assignment for updating multiple references to avoid accidental mutation.
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:
-
Augmented operators perform inplace modification and behave differently than standard operators in some cases.
-
Know the full list of arithmetic, bitwise, and sequence augmented assignment operators.
-
Use augmented assignment to write concise and efficient updates to variables and sequences.
-
Be mindful of right-associativity order of evaluation and behavior with mutable types to avoid bugs.
I hope this guide gives you a comprehensive understanding of augmented assignment in Python. Use these operators appropriately to write clean, idiomatic Python code.