A Comprehensive Guide to Augmented Assignment Operators in Python
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
What are augmented assignment operators, arithmetic augmented assignments, bitwise augmented assignments, sequence augmented assignments, advantages of augmented assignment operators, augmented assignment with mutable types, operator precedence and order of evaluation, updating multiple references, augmented assignment vs normal assignment, comparisons to other languages, best practices and style guide.
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:
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.
These perform the standard arithmetic operations like addition or exponentiation and assign the result back to the variable.
These allow you to perform bitwise AND, OR, XOR, right shift, and left shift operations combined with assignment.
The += operator can also be used to concatenate sequences like lists, tuples, and strings.
These operators provide a shorthand for sequence concatenation.
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 than x = 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 assignments act inplace and modify the existing object. This can be problematic with mutable types like lists:
In contrast, normal operators with immutable types create a new object:
So be careful when using augmented assignments with mutable types, as they modify the object in-place rather than creating a new object.
Augmented assignment operators have right-associativity. This can cause unexpected results:
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:
When you augmented assign to a variable, it updates all references to that object:
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:
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.
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.
Here are some best practices when using augmented assignments in Python:
Use whitespace around the operators: x += 1 rather than x+=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 than x = x + 1 and x = 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.
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.
- python
- variables-and-operators
Start Learning
Data Science
Future Tech
IIT Courses
Accelerator Program in
Business Analytics and Data Science
In collaboration with
Certificate Program in
Financial Analysis, Valuation, & Risk Management
DevOps & Cloud Engineering
Strategic Management and Business Essentials
Assignment Operators in Python – A Comprehensive Guide
Updated on July 27, 2024
Ever felt confused about assigning values to variables in Python ? Wondering how to simplify operations like addition, subtraction, or even bitwise shifts?
Many of us face these questions when diving into Python programming .
Assignment operators in Python are here to make our lives easier. These operators help us assign values to variables in a clean and efficient way and make our code efficient and compact.
We’ll explore how these operators work and how we can use them to streamline our code.
Basic Assignment Operator
Let’s start with the basics.
The equal sign (=) is the simple assignment operator in Python. It assigns the value on its right to the variable on its left.
In this example:
- We assign the values 10 to a and 5 to b.
- We add a and b and assign the result to c.
- We print the value of c, which is 15.
Augmented Assignment Operators in Python
Now, let’s move on to augmented assignment operators.
These operators combine an operation with an assignment in one step. They make our code more concise and easier to read.
Addition Assignment Operator (+=)
How It Works: This operator would thus add to the right operand and assign the result to the left operand.
Here, a is initially 10.
The ‘+=’ operator adds 5 to a and assigns the result back to a. So, a becomes 15.
Subtraction Assignment Operator (-=)
How It Works: It subtracts the right operand from the left operand and assigns the result to the left operand.
Initially, a is 10.
The ‘-=’ operator subtracts 5 from a and assigns the result back to a. Thus, a becomes 5.
Multiplication Assignment Operator (*=)
How It Works: This is the operator for multiplication of the left operand by the right operand, with the result being assigned to the left operand.
The ‘*=’ operator multiplies a by 5 and assigns the result back to a. Hence, a becomes 50.
Division Assignment Operator (/=)
How It Works: It divides the left operand by the right and assigns the outcome to the left operand.
The ‘/=’ operator divides a by 5 and assigns the result back to a. Thus, a becomes 2.0.
Modulus Assignment Operator (%=)
How It Works: This operator divides the left operand by the right operand and assigns the remainder to the left operand.
The ‘%=’ operator divides a by 3 and assigns the remainder back to a. Therefore, a becomes 1.
Floor Division Assignment Operator (//=)
How It Works: It performs floor division of the left operand by the right operand and, therefore, modifies the value of the left operand.
The ‘//=’ operator divides a by 3 and assigns the floor value back to a. So, a becomes 3.
Exponentiation Assignment Operator (**=)
How It Works: The operator raises the left operand to the power of the right one and puts the result back into the left operand.
Initially, a is 2.
The ‘**=’ operator raises a to the power of 3 and assigns the result back to a. Therefore, a becomes 8.
Bitwise AND Assignment Operator (&=)
How It Works: It performs a bitwise AND operation on the operands and assigns the result to the left operand.
Initially, a is 5 (0101 in binary).
The ‘&=’ operator performs a bitwise AND with 3 (0011 in binary) and assigns the result back to a. Thus, a becomes 1 (0001 in binary).
Bitwise OR Assignment Operator (|=)
How It Works: This operator performs a bitwise OR operation on the operands and assigns the result to the left operand.
The ‘|=’ operator performs a bitwise OR with 3 (0011 in binary) and assigns the result back to a. So, a becomes 7 (0111 in binary).
Bitwise XOR Assignment Operator (^=)
How It Works: It performs a bitwise XOR operation on the operands and assigns the result to the left operand.
The ‘^=’ operator performs a bitwise XOR with 3 (0011 in binary) and assigns the result back to a. Thus, a becomes 6 (0110 in binary).
Bitwise Right Shift Assignment Operator (>>=)
How It Works: This operator performs a bitwise right shift on the left operand and assigns the result to the left operand.
Initially, a is 8 (1000 in binary).
The ‘>>=’ operator right shifts a by 2 and assigns the result back to a. So, a becomes 2 (0010 in binary).
Bitwise Left Shift Assignment Operator (<<=)
How It Works: It performs a bitwise left shift on the left operand and assigns the result to the left operand.
Initially, a is 3 (0011 in binary).
The ‘<<=’ operator left shifts a by 2 and assigns the result back to a. Therefore, a becomes 12 (1100 in binary).
Introducing the Walrus Operator (:=)
Ever wondered if there’s a way to simplify assignments within expressions?
Meet the Walrus Operator.
The Walrus Operator (:=) allows us to assign values to variables as part of an expression. It makes our code more concise and readable.
Imagine you’re iterating over a list and want to process elements until the list becomes short. The Walrus Operator lets us do this efficiently.
- n is assigned the length of a within the while loop condition.
- The loop runs until a has two or fewer elements.
- We reduce our code’s length without sacrificing clarity.
Practical Examples of Assignment Operators
Let’s dive into more practical examples of assignment operators in Python.
These examples will help us see how assignment operators make our code cleaner and more efficient.
Addition Assignment Operator (+=):
- We use the += operator to accumulate the sum of numbers from 0 to 4.
Subtraction Assignment Operator (-=):
- We use the -= operator to update the balance after each withdrawal.
Multiplication Assignment Operator (*=):
Division Assignment Operator (/=):
Modulus Assignment Operator (%=):
Floor Division Assignment Operator (//=):
Exponentiation Assignment Operator (**=):
Bitwise AND Assignment Operator (&=):
Bitwise OR Assignment Operator (|=):
Bitwise XOR Assignment Operator (^=):
Bitwise Right Shift Assignment Operator (>>=):
Bitwise Left Shift Assignment Operator (<<=):
Mastering assignment operators in Python can significantly improve our coding skills. These operators help us write cleaner, more efficient code. In this comprehensive guide, we explored assignment operators in Python, from the basic operator to the more advanced augmented operators and the Walrus Operator.
Whether we’re using simple assignments or the Walrus Operator, understanding these tools is essential. As we practice and apply these operators, our Python programming becomes more intuitive and effective.
- = operator is used for value assignment.
- == does a comparison to check if the two values are equal.
- += operator adds the right operand to the left operand and assigns the result to the left operand.
- + simply adds the operands without assignment.
Programs tailored for your success
3 ASSURED INTERVIEWS
Part-time · 10 months
Apply by : 17 November, 2024
Download Brochure
Part-time · 7 months
INTERNSHIP ASSURANCE
Part-time · 7.5 months
Part-time · 6 months
Upskill with expert articles
Accelerator Program in Business Analytics & Data Science
Integrated Program in Data Science, AI and ML
Accelerator Program in AI and Machine Learning
Advanced Certification Program in Data Science & Analytics
Certification Program in Data Analytics
Certificate Program in Full Stack Development with Specialization for Web and Mobile
Certificate Program in DevOps and Cloud Engineering
Certificate Program in Application Development
Certificate Program in Cybersecurity Essentials & Risk Assessment
Integrated Program in Finance and Financial Technologies
Certificate Program in Financial Analysis, Valuation and Risk Management
Certificate Program in Strategic Management and Business Essentials
Executive Program in Product Management
Certificate Program in Product Management
Certificate Program in Technology-enabled Sales
Certificate Program in Gaming & Esports
Certificate Program in Extended Reality (VR+AR)
Professional Diploma in UX Design
© 2024 Hero Vired. All rights reserved
Chapter 2B: Assignment Operators
Bonus chapter on augmented assignment operators and unary operators, chapter objectives.
We’ve learned how to define a variable with the assignment operator ( = ), and now we’ll look at a few closely related operators - the augmented assignment operators . We’ll also learn about the unary arithmetic operators .
In this chapter you will:
- Learn what the augmented assignment operators and unary arithmetic operators are, and how they’re used,
- Practise using the augmented assignment operators and unary arithmetic operators.
Augmented assignment operators
What’s an augmented assignment operator.
In the previous chapter we used the basic assignment operator ( = ) to define and overwrite variables. We also saw how variables can be used in calculations:
When using the assignment operator, it’s actually valid for the right hand side of the assignment to reference the variable that’s being assigned to! For example:
my_number = my_number + 1 means that my_number is assigned the current value of my_number (i.e. 2) plus 1.
Incrementing a variable like this is pretty common, so Python includes an operator that provides a shortcut:
+= is known as an augmented assignment operator , because it’s actually a combination of two operations:
- Adding a number to the variable’s current value ( + ),
- Assigning the updated value back to the variable ( = ).
Augmented assignment operators are sometimes called compound assignment operators .
You can also use += to increment a variable by the value of a different variable:
What augmented assignment operators are available?
+= is perhaps the most commonly used augmented assignment operator, but there’s actually quite a few others. In fact, each of the arithmetic operators we covered in chapter 2 has a corresponding augmented assignment operator:
They each work in a similar way to += . For example, my_number **= 3 means that my_number is assigned the current value of my_number raised to the power of 3.
Revisiting storage boxes
In the previous chapter we thought of variables as storage boxes, and each variable’s value as the item in its box. We can expand this analogy to describe how augmented assignment operators work:
The effect is exactly the same either way. The += is just a prettier shorthand for the same instruction.
Unary arithmetic operators
What are the unary arithmetic operators.
Throughout the previous chapters we’ve seen how + and - can be used as arithmetic operators for addition and subtraction:
When using + and - to add or subtract, the operator is surround by two operands (e.g. 1 + 2 ). However, + and - can also be used as a prefix for a single operand (e.g. +1 or -1 ). When + and - are used like this, they’re known as the unary arithmetic operators :
As you might expect, putting - before an expression changes its sign:
Putting + before an expression doesn’t change its sign. It is almost always true that the unary + operator has no impact, i.e. x is equal to +x . There are certain niche scenarios with other data types where this is not strictly true, but it mainly exists for symmetry: you may sometimes find it helps readability to treat positive and negative numbers the same.
What’s the precedence of the unary arithmetic operators?
This table lists the arithmetic operators that we’ve seen so far from highest precedence to lowest. Operators on the same row have the same precedence.
The only arithmetic operator with a higher precedence than the unary arithmetic operators is the exponentiation operator ( ** ). This can lead to surprising results:
In this example, -2 ** 2 is equivalent to -(2 2 ), which is equal to -4.
In situations like this, it’s helpful to use brackets for clarification:
Other resources
If you’d like to read some alternate explanations, or see some more examples, then you might find these resources helpful:
- This site has a tutorial on expressions that covers the augmented assignment operators.
- This site has a tutorial on operators that covers the augmented assignment operators and unary arithmetic operators.
Practice exercises
We’ve run through the general concepts, and now we’ll get some hands-on experience.
It can be tempting to jump right into running each exercise in the REPL, but it’s best to try and predict the answers first. That way, you’ll have a clearer idea about which concepts you find more or less intuitive.
You can check your answers for each exercise at the end of this chapter.
Exercise 2.11
Exercise 2.12, exercise 2.13, exercise 2.14, exercise 2.15, exercise 2.16, exercise 2.17, exercise 2.18, troubleshooting exercises.
There’s a few issues that people can run into when using augmented assignment operators and unary arithmetic operators in Python. We’ve listed some of the most common ones here.
For each troubleshooting exercise, try and figure out what went wrong and how it can be fixed.
Exercise 2.19
Why is an error being printed?
Exercise 2.20
Exercise 2.21, exercise 2.22.
Why do my_first_number and my_second_number have different values?
Exercise 2.23
Why do these expressions have different values?
Exercise 2.24
We’ve reached the end of assignment operators, and at this point you should know:
- What the augmented assignment operators and unary arithmetic operators are,
- How to use augmented assignment operators to simplify updating variables,
- How to use arithmetic operators to change the sign of an expression.
Next up is Chapter 3: Data Types .
The += augmented assignment operator is a combination of addition and assignment to a variable. In particular, 5 += 7 is equivalent to 5 = 5 + 7 . We’re trying to assign to a value (i.e. 5) instead of a variable, which isn’t valid.
*= is an augmented assignment operator. The * and = have to be used in this order, without any characters in between.
/= is an augmented assignment operator. =/ looks very similar to /= (the augmented assignment operator) but the operators are in the opposite order, which isn’t valid.
-= is an augmented assignment operator. my_first_number -= 3 means that my_first_number is assigned the current value of my_first_number (i.e. 7) minus 3.
=- looks very similar to -= (the augmented assignment operator), but it’s handled differently. Python evaluates =- by separating it into an assignment operator ( = ) and a unary arithmetic operator ( - ). In this case, my_second_number =- 3 is evaluated as my_second_number =(- 3) .
The unary arithmetic operators ( + and - ) have lower precedence than the exponentiation operator ( ** ). In the first expression, 3 ** 2 is calculated first (evaluating to 9), and then - flips the sign (evaluating to -9). In the second expression, -3 is squared, evaluating to 9.
Augmented assignment operators can only be used on variables that have already been defined. my_number *= 2 means that my_number is assigned the current value of my_number multiplied by 2. However, my_number hasn’t been defined, so it doesn’t currently have a value, making the command invalid.
IMAGES
VIDEO