Python Assignment Operators 

Python Assignment Operators 

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 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()

Name Binding

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 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. 

Example:

Python

Output: 

Chained Assignment Operator in Python

Explanation: Using the concept of chained assignment, a, b, and c were assigned 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 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.

OperatorExampleEquivalentDescription
+=x += yx = x + yAdd and assign
-=x -= yx = x – ySubtract and assign
*=x *= yx = x * yMultiply and assign
/=x /= yx = x / yDivide and assign
//=x //= yx = x // yFloor Divide and assign
%=x %= yx = x % yEvaluate modulo and assign
**=x **= yx = x ** yCalculate the exponent and assign

Bitwise Augmented Operators in Python

The bitwise augmented operators work similarly to the arithmetic 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.

OperatorExampleEquivalentDescription
&=x &= yx = x & yDo a bitwise AND, then assign
^=x ^= yx = x ^ yDo bitwise XOR, then assign
>>=x >>= yx = x >> yEvaluate Bitwise Right Shift, then assign
<<=x <<= yx = x << yCalculate 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 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.

Python Walrus Operator

This is a special kind of assignment operator 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. 

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. 

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.

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 use more than one assignment operator in one line in Python?

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

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