Python Assignment Operators 

blog-3.jpg

The Python assignment operator is used to give a variable a value. Instead of putting the value directly in a memory location, the variable just points to the value in memory. Python supports augmented assignment operators, also known as compound operators, that make your code run faster. The new version of Python released the concept of the walrus operator, which allows you to assign values to variables as a part of an expression. In this article, you will learn about all these concepts with the help of real-world examples. 

Table of Contents:

What is an Assignment Statement in Python?

An assignment statement is made up of a variable (the target), a value (the object), and the assignment operator (=), which binds the variable to the value. The assignment operator in Python is one of the crucial operators in Python

The general syntax for an assignment statement is 

variable = expression

Examples:

  • name = “Alice”
  • age = 30
  • items = [10, 20, 30]
  • x = y = z = 0
  • total_cost = price * quantity + tax
  • def get_status():
    return “active”
    status = get_status()

Understanding Name Binding in Python Variable Assignment

In Python, variables are not actual containers that have a value inside them. They are just names used to refer to the container that holds the value. This also means that you can have multiple variables acting as a reference to a single value.


Example:

Python

Output:

Name Binding

Explanation: In this example, both x and y refer to the same integer object, 10.

Chained Assignment Operator in Python

Chaining an operator means that you can have multiple Python operators in the same expression. In the case of the Assignment Operator, it means you can assign the same value to more than one variable.  This is an example of assigning multiple variables in one line.

Example of Assigning Multiple Variables in One Line:

Python

Output: 

Chained Assignment Operator in Python

Explanation: Using the concept of chained assignment, a, b, and c, assigning multiple variables in one line to get the same value of 10.

Augmented Assignment Operators in Python

Augmented assignment operators, also known as compound operators, combine the arithmetic and bitwise operators with the assignment operator. When you use an augmented operator, you evaluate the expression and assign the result to the variable at the same time. It is two steps combined in one step. This simplifies the code and works faster with mutable objects. Mutable objects are those objects that can be modified after declaration. 

Arithmetic Augmented Operators in Python

In Python, we have seven arithmetic operators and, therefore, seven augmented arithmetic operators. The assignment operator in Python is right-associative, which means that the expression gets evaluated from right to left. Hence, first, the calculation happens, and then the result gets assigned to the variable. 

  • Let us take x -= y for example. 
  • x -= y is equivalent to x = x – y. 
  • First, x-y is evaluated.
  • Then, the result is assigned to x.

Example:

Python

Output:

Arithmetic Augmented Operators in Python

Explanation: This code prints the value of x after each arithmetic augmented assignment operation. The same principle applies to all of them.

Below, you will find a table containing all the arithmetic augmented operators in Python.

Operator Example Equivalent Description
+= x += y x = x + y Add and assign
-= x -= y x = x – y Subtract and assign
*= x *= y x = x * y Multiply and assign
/= x /= y x = x / y Divide and assign
//= x //= y x = x // y Floor divide and assign
%= x %= y x = x % y Evaluate modulo and assign
**= x **= y x = x ** y Exponentiate and assign

Bitwise Augmented Operators in Python

The bitwise Python augmented operators work similarly to the arithmetic Python operators. We just consider the binary values of the operands and then perform calculations. It works on the same principle and is evaluated in the same manner. Let us look at an example. 

Example:

Python

Output:

Bitwise Augmented Operators in Python

Explanation: Here, the binary values of 10, 3, and 2 are used to carry out the calculations.

Operator Example Equivalent Description
&= x &= y x = x & y Do a bitwise AND, then assign
^= x ^= y x = x ^ y Do bitwise XOR, then assign
>>= x >>= y x = x >> y Evaluate Bitwise Right Shift, then assign
<<= x <<= y x = x << y Calculate the Bitwise Left Shift and assign

Behavior of Augmented Operator in Python

The augmented operator works differently for mutable and immutable objects in Python. Let us learn about it one by one with examples.

Assignment with Immutable Objects in Python 

Immutable objects can not be modified after declaration. In Python, immutable objects are int, bool, float, str, and tuple. If you try to change a variable referring to an immutable object, it will simply create a new object at a different memory location, and the variable will refer to the new object now. 

Let us understand what happens step by step with the help of an example. 

Let us take x = 8 and then modify it to 5 using  x = 5

  • First, x is referring to the container that holds the value 8. 
  • When you code x = 5, it creates a new integer value at a different memory location.
  • x then rebinds itself to this new object, ‘5’, leaving the old object, ‘8’.
  • Now, the ‘8’ object no longer has any reference. The ‘8’ object gets destroyed after some time by Python’s garbage collector. 

Example:

Python

Output:

Assignment with Immutable Objects in Python

Explanation: Even though the operation seems to modify x, it creates a new object, ‘6’, and rebinds the variable x to it. The original object ‘5’ remains unchanged and will be destroyed by the garbage collector after some time.

Assignment with Mutable Objects in Python

Mutable objects are those that can be modified after their declaration. In Python, mutable objects are lists, dictionaries, and sets. Augmented Python operators can modify the object in place. This means it will modify the existing variable without creating a new one. 

Example:

Python

Output:

Assignment with Mutable Objects in Python

Explanation: As you can see, the old object is modified without creating a new object at a new memory location.

Mutable vs Immutable Object Behavior in Assignments

Aspect Mutable Objects Immutable Objects
Definition Objects whose value can be changed after assignment Objects whose value cannot be changed after assignment
Examples Lists, dictionaries, sets Integers, strings, tuples, floats, booleans
Behavior in Assignment Changes to the object affect all references Reassignment creates a new object in memory
Memory Reference All variables point to the same object Each assignment creates a new reference
Effect of Augmented Assignment Modifies the original object in place Creates a new object and rebinds the variable
Python Assignment Operator Result Efficient with in-place updates Less efficient due to object recreation
Code Example lst = [1, 2]; lst += [3] → updates lst x = 5; x += 1 → creates a new int object
Garbage Collection Impact Object remains until all references are gone Value tracking, constants, and simple variables
Common Use Cases Building data structures, managing state Value tracking, constants, simple variables

Difference Between = and == in Python

Feature = (Assignment Operator) == (Equality Operator)
Purpose Assigns a value to a variable Compares two values
Usage x = 5 x == 5
Result Assigns the value to the variable Returns True or False
Can be used in conditions? No Yes
Used for binding or logic? Binding a name to a value Logic testing

Python Walrus Operator

This is a special kind of assignment operator in Python introduced in Python 3.8. Walrus operators allow you to evaluate an expression or a condition and assign the result at the same time using a single line of code. 

The general syntax of this operator is as follows:

variable := expression

The result of the expression is evaluated and assigned to the variable. Then it is returned as the result of the overall expression. 

walrus operator example:

Python

Output:

Python Walrus Operator

Explanation: 

  • Here, the expression (square := n * n) first calculates the square of n and assigns it to the variable square. Then, the condition square > 100 is checked on the same line, and if the condition is true, the value of square is appended to the list.
  • Without the walrus operator, the square is calculated first. Then, it gets checked against 100 and appended to the list if the condition passes.
  • With the walrus operator, both steps happen in one go. The square is calculated and assigned within the condition, and if it exceeds 100, it’s added to the ‘squares’ list. 

When to Use the Walrus Operator in Python?

The := operator, also known as the walrus operator in Python, was introduced in Python 3.8. It allows you to assign a value to a variable as part of an expression, making your code more concise and often more efficient.

1. Assignment Within While Loops
When looping until a condition is no longer met, the walrus operator can help avoid repetitive Python assignment lines.
Example:

while (line := input("Enter text: ")) != "quit":
print(f"You typed: {line}")

Why use it: Avoids assigning the same value outside and inside the loop.

2. Reducing Redundant Function Calls
If you need to check the result of a function now or use it later, the := operator Python saves you from calling it twice.
Example:

if (length := len(my_list)) > 5:
print(f"List is too long: {length} items")

Why use it: Enhances performance by avoiding unnecessary recomputation while keeping the condition and assignment in one readable line.

3. In List Comprehensions or Generator Expressions
The walrus operator in Python is perfect for capturing intermediate results inside expressions like list comprehensions.
Example:

results = [n for n in data if (squared := n * n) > 50]

Why use it: Streamlines logic by avoiding extra loops or nested conditions, especially in walrus operator examples where efficiency matters.

4. Logging or Debugging in Conditional Expressions
While debugging or logging, use the Python assignment operator inline to capture values without breaking the flow.
Example:

if (error := check_errors()):
print(f"Error found: {error}")

Why use it: It improves traceability while keeping conditions and debug outputs tightly coupled.

5. Simplifying Data Processing Pipelines
In large data-processing blocks, you can reduce variable noise by combining computation and assignment using the walrus operator in Python syntax.
Example:

if (avg := sum(scores) / len(scores)) > 90:
print(f"Excellent! Average score is {avg}")

Why use it: Keeps your logic pipeline clean, especially in data science scripts or real-time processing tasks.

Common Mistakes Using Assignment Operators in Python

1. Confusing Assignment (=) with Comparison (==)
One of the most widespread issues among beginners is mistaking the Python assignment operator for the equality operator. While the assignment operator in Python is used to assign a value to a variable, the equality operator checks whether two values are the same. Using one in place of the other leads to syntax or logical errors. This is a foundational concept and must be clearly understood to avoid serious logic bugs.

2. Misunderstanding Augmented Assignment Behavior
Augmented assignment operators (like +=, -=, etc.) in Python behave differently depending on whether you’re dealing with mutable or immutable objects. Many mistakenly assume that these Python operators always update the value in place. However, with immutable objects like numbers or strings, a new object is created, and the variable is rebound to that new object. This difference in behavior can lead to unexpected results if not properly understood.

3. Misusing the Walrus Operator (:=) in Unsupported Python Versions
The walrus operator was introduced in Python 3.8 and is used for assigning a value as part of an expression. A common mistake is trying to use this operator in older Python versions, where it is not supported, leading to syntax errors. It’s also often misused in contexts where it doesn’t improve readability, violating the Pythonic principle that “Readability counts.”

4. Assuming Chained Assignments in Python to Create Independent Copies
With chained assignments in Python, a single value is assigned to multiple variables in one statement. A common misunderstanding is thinking each variable gets its own copy of the value. In reality, all variables refer to the same object in memory. This is especially problematic with mutable objects, where changes through one variable affect all others.

5. Expecting Assignment to Be an Expression
Another subtle but critical mistake is assuming that an assignment in Python can return a value and be used as part of an expression. Unlike some other languages, Python treats assignment as a statement, not an expression. This means it cannot be embedded in other statements like conditionals—unless you’re using the walrus operator. Misunderstanding this behavior often leads to design flaws and syntax issues in Python code.

Conclusion

Assignment operators are a fundamental part of Python and have a significant role in how values are stored, changed, and controlled in your program. Python uses name binding rather than treating variables as containers. Augmented assignment operators make operations simpler by grouping arithmetic or bitwise computations with assignment, reducing code length and frequently improving efficiency. You also learned about the walrus operator (:=), an advanced feature supporting assignments in expressions that eliminate redundancy and make conditions more expressive and compact.

To take your skills to the next level, check out this Python training course and gain hands-on experience. Also, prepare for job interviews with Python interview questions prepared by industry experts.

 

These blog posts cover key Python Basics, including file operations and module usage-

How to Parse a String to a Float or Int in Python – Explore various techniques in Python for converting strings into integers or floating-point numbers.
Python Arithmetic Operators – Gain insight into how Python handles arithmetic operations through its built-in operators.
Python Comparison Operators – Uncover the different comparison operators that Python provides to evaluate expressions.
Python Bitwise Operators – Dive into Python’s bitwise operators to learn how binary-level operations are performed.
Python Membership and Identity Operators – Take a closer look at how Python uses membership and identity operators to compare objects and values.
Python Docstrings – Learn the purpose and structure of Python docstrings to document your code effectively.
Access Environment Variable Values in Python – Master the technique of retrieving environment variable values within a Python script.
Python: How to Get the Last Element of List – Find out how to access the last element of a list using different Python methods.
Access Index Using For Loop in Python – See how to access index positions while iterating over a list using a for loop in Python.

Python Assignment Operators – FAQs

Q1. Can assignment operators be chained in Python?

Yes, you can chain assignment operators, e.g., a = b = c = 5, which sets the value of 5 to all three variables.

Q2. What is the difference between = and == in Python?

The = operator is employed to set values into variables, whereas == is employed to compare equality between two values.

Q3. Can the += operator change immutable types like strings?

No, += does not change the original string but creates a new string because strings are immutable in Python.

Q4. What occurs when an assignment operator is applied to a list in Python?

When applied to a list, assignment operators such as += or *= change the list in place because lists are mutable objects in Python.

Q5. Is it possible to assign a single value to multiple variables?

Yes, you can also chain several assignment operators on one line (x = y = z = 10), assigning the same value to each variable.

Q6. How to assign values to variables in Python?

Use = to assign a value to a variable, like x = 10.

Q7. What is the purpose of assignment operators in Python?

They assign values and update variables, e.g., x += 5 adds 5 to x.

Q8. What is the walrus operator in Python?

The := operator assigns a value and returns it in a single expression.

Q9. Can I use += or = with immutable data types?

Yes, but it creates a new object since immutable types like int and str can’t be changed in place.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner