close
The Wayback Machine - https://web.archive.org/web/20240922224026/https://www.geeksforgeeks.org/assignment-operators-in-python/
Open In App

Assignment Operators in Python

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python.

Operators

Sign

Description

Syntax

Assignment Operator

=

Assign the value of the right side of the expression to the left side operandc = a + b 

Addition Assignment Operator

+=

Add right side operand with left side operand and then assign the result to left operanda += b   

Subtraction Assignment Operator

-=

Subtract right side operand from left side operand and then assign the result to left operanda -= b  

Multiplication Assignment Operator

*=

Multiply right operand with left operand and then assign the result to the left operanda *= b     

Division Assignment Operator

/=

Divide left operand with right operand and then assign the result to the left operanda /= b

Modulus Assignment Operator

%=

Divides the left operand with the right operand and then assign the remainder to the left operanda %= b  

Floor Division Assignment Operator

//=

Divide left operand with right operand and then assign the value(floor) to left operanda //= b   

Exponentiation Assignment Operator

**=

Calculate exponent(raise power) value using operands and then assign the result to left operanda **= b     

Bitwise AND Assignment Operator

&=

Performs Bitwise AND on operands and assign the result to left operanda &= b   

Bitwise OR Assignment Operator

|=

Performs Bitwise OR on operands and assign the value to left operanda |= b    

Bitwise XOR Assignment Operator

^=

Performs Bitwise XOR on operands and assign the value to left operanda ^= b    

Bitwise Right Shift Assignment Operator

>>=

Performs Bitwise right shift on operands and assign the result to left operanda >>= b     


Bitwise Left Shift Assignment Operator

<<=

Performs Bitwise left shift on operands and assign the result to left operanda <<= b 

Walrus Operator

:=

Assign a value to a variable within an expression

a := exp

Here are the Assignment Operators in Python with examples.

Assignment Operator

Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand.

Python
# Assigning values using 
# Assignment Operator 
a = 3
b = 5

c = a + b 

# Output 
print(c)

Output

8

Addition Assignment Operator

The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand.

Syntax: a += b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the addition assignment operator which will first perform the addition operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a + b
a += b

# Output
print(a)

Output:

8

Subtraction Assignment Operator

The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-hand side operand and then assigning the result to the left-hand side operand.

Syntax: a -= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the subtraction assignment operator which will first perform the subtraction operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a - b
a -= b

# Output
print(a)

Output:

-2

Multiplication Assignment Operator

The Multiplication Assignment Operator is used to multiply the right-hand side operand with the left-hand side operand and then assigning the result to the left-hand side operand.

Syntax: a *= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the multiplication assignment operator which will first perform the multiplication operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a * b
a *= b

# Output
print(a)

Output:

15

Division Assignment Operator

The Division Assignment Operator is used to divide the left-hand side operand with the right-hand side operand and then assigning the result to the left operand.

Syntax: a /= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the division assignment operator which will first perform the division operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a / b
a /= b

# Output
print(a)

Output:

0.6

Modulus Assignment Operator

The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands and then takes the remainder and assigns it to the left operand.

Syntax: a %= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the modulus assignment operator which will first perform the modulus operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a % b
a %= b

# Output
print(a)

Output:

3

Floor Division Assignment Operator

The Floor Division Assignment Operator is used to divide the left operand with the right operand and then assigs the result(floor value) to the left operand.

Syntax: a //= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the floor division assignment operator which will first perform the floor division operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a // b
a //= b

# Output
print(a)

Output:

0

Exponentiation Assignment Operator

The Exponentiation Assignment Operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

Syntax: a **= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the exponentiation assignment operator which will first perform exponent operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a ** b
a **= b

# Output
print(a)

Output:

243

Bitwise AND Assignment Operator

The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands and then assigning the result to the left operand.

Syntax: a &= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise AND assignment operator which will first perform Bitwise AND operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a & b
a &= b

# Output
print(a)

Output:

1

Bitwise OR Assignment Operator

The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and then assigning result to the left operand.

Syntax: a |= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise OR assignment operator which will first perform bitwise OR operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a | b
a |= b

# Output
print(a)

Output:

7

Bitwise XOR Assignment Operator 

The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands and then assigning result to the left operand.

Syntax: a ^= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise XOR assignment operator which will first perform bitwise XOR operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a ^ b
a ^= b

# Output
print(a)

Output:

6

Bitwise Right Shift Assignment Operator

The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the operands and then assign result to the left operand.

Syntax: a >>= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise right shift assignment operator which will first perform bitwise right shift operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a >> b
a >>= b

# Output
print(a)

Output:

0

Bitwise Left Shift Assignment Operator

The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the operands and then assign result to the left operand.

Syntax: a <<= b

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise left shift assignment operator which will first perform bitwise left shift operation and then assign the result to the variable on the left-hand side.

Python
a = 3
b = 5

# a = a << b
a <<= b

# Output
print(a)

Output:

96

Walrus Operator

The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.

Syntax: a := expression

Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop. The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.

Python
# a list
a = [1, 2, 3, 4, 5]

# walrus operator
while(x := len(a)) > 2:
    a.pop()
    print(x)

Output:

5
4
3

Assignment Operators in Python – FAQs

What are Assignment Operators in Python?

Assignment operators in Python are used to assign values to variables. These operators can also perform additional operations during the assignment. The basic assignment operator is =, which simply assigns the value of the right-hand operand to the left-hand operand. Other common assignment operators include +=, -=, *=, /=, %=, and more, which perform an operation on the variable and then assign the result back to the variable.

What is the := Operator in Python?

The := operator, introduced in Python 3.8, is known as the “walrus operator”. It is an assignment expression, which means that it assigns values to variables as part of a larger expression. Its main benefit is that it allows you to assign values to variables within expressions, including within conditions of loops and if statements, thereby reducing the need for additional lines of code.

Here’s an example:

# Example of using the walrus operator in a while loop
while (n := int(input("Enter a number (0 to stop): "))) != 0:
print(f"You entered: {n}")

This loop continues to prompt the user for input and immediately uses that input in both the condition check and the loop body.

What is the Assignment Operator in Structure?

In programming languages that use structures (like C or C++), the assignment operator = is used to copy values from one structure variable to another. Each member of the structure is copied from the source structure to the destination structure. Python, however, does not have a built-in concept of ‘structures’ as in C or C++; instead, similar functionality is achieved through classes or dictionaries.

What is the Assignment Operator in Python Dictionary?

In Python dictionaries, the assignment operator = is used to assign a new key-value pair to the dictionary or update the value of an existing key. Here’s how you might use it:

my_dict = {}  # Create an empty dictionary
my_dict['key1'] = 'value1' # Assign a new key-value pair
my_dict['key1'] = 'updated value' # Update the value of an existing key
print(my_dict) # Output: {'key1': 'updated value'}

What is += and -= in Python?

The += and -= operators in Python are compound assignment operators. += adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand. Conversely, -= subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand.

Here are examples of both:

# Example of using +=
a = 5
a += 3 # Equivalent to a = a + 3
print(a) # Output: 8

# Example of using -=
b = 10
b -= 4 # Equivalent to b = b - 4
print(b) # Output: 6

These operators make code more concise and are commonly used in loops and iterative data processing.



Previous Article
Next Article

Similar Reads

Augmented Assignment Operators in Python
An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write "a = 5" to assign value 5 to variable 'a'. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator
4 min read
Increment += and Decrement -= Assignment Operators in Python
If you're familiar with Python, you would have known Increment and Decrement operators ( both pre and post) are not allowed in it. Python is designed to be consistent and readable. One common error by a novice programmer in languages with ++ and -- operators are mixing up the differences (both in precedence and in return value) between pre and post
3 min read
A += B Assignment Riddle in Python
Predict the output of these two expressions on Python console On console Geek = (1, 2, [8, 9]) Geek[2] += [3, 4] Output: Explanation: Look at the bytecode Python generates for the expression s[a] += b. It becomes clear how that happens. It works step by step Put the value of s[a] on Top Of Stack(TOS). Perform TOS += b. This succeeds, If TOS refers
1 min read
Python Indexerror: list assignment index out of range Solution
In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range. Python Indexerror: list assignment index out of range ExampleIf ‘fruits’ is a list, fruits=[‘Apple’,’ Banan
3 min read
Python | Operators | Question 1
What is the output of the following code : C/C++ Code print 9//2 (A) 4.5 (B) 4.0 (C) 4 (D) Error Answer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number. Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 2
Which function overloads the &gt;&gt; operator? (A) more() (B) gt() (C) ge() (D) None of the above Answer: (D) Explanation: rshift() overloads the &gt;&gt; operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 3
Which operator is overloaded by the or() function? (A) || (B) | (C) // (D) / Answer: (B) Explanation: or() function overloads the bitwise OR operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 4
What is the output of the following program : C/C++ Code i = 0 while i (A) 0 2 1 3 2 4 (B) 0 1 2 3 4 5 (C) Error (D) 1 0 2 4 3 5 Answer: (C)Explanation: There is no operator ++ in Python Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Python 3 - Logical Operators
Logical Operators are used to perform certain logical operations on values and variables. These are the special reserved keywords that carry out some logical computations. The value the operator operates on is known as Operand. In Python, they are used on conditional statements (either True or False), and as a result, they return boolean only (True
4 min read
How To Do Math in Python 3 with Operators?
Python3 provides us data types like integer and float along with various operators to perform mathematical calculations for graph plotting, machine learning algorithms, Statistical, data analytical purposes. An operator is a symbol that performs specific operations, which is very useful if one is frequently dealing with numbers. Operator precedence
5 min read
Precedence and Associativity of Operators in Python
In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes into play, determining the order of evaluation. Opera
4 min read
Inplace Operators in Python | Set 1 (iadd(), isub(), iconcat()...)
Python in its definition provides methods to perform inplace operations, i.e. doing assignments and computations in a single statement using an operator module. Example x += y is equivalent to x = operator.iadd(x, y) Inplace Operators in PythonBelow are some of the important Inplace operators in Python: iadd()isub()iconcat()imul()itruediv()imod()ia
3 min read
Inplace Operators in Python | Set 2 (ixor(), iand(), ipow(),…)
Inplace Operators in Python | Set 1(iadd(), isub(), iconcat()…) More functions are discussed in this articles. 1. ixor() :- This function is used to assign and xor the current value. This operation does "a^ = b" operation. Assigning is not performed in case of immutable containers, such as strings, numbers and tuples. 2. ipow() :- This function is
3 min read
Inplace vs Standard Operators in Python
Inplace Operators - Set 1, Set 2Normal operators do the simple assigning job. On other hand, Inplace operators behave similarly to normal operators except that they act in a different manner in case of mutable and Immutable targets. The _add_ method, does simple addition, takes two arguments, returns the sum, and stores it in another variable witho
3 min read
Chaining comparison operators in Python
Checking more than two conditions is very common in Programming Languages. Let's say we want to check the below condition: a &lt; b &lt; c The most common syntax to do it is as follows: if a &lt; b and b &lt; c : {...} In Python, there is a better way to write this using the Comparison operator Chaining. The chaining of operators can be written as
5 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.  OPERATORS: These are the special symbols. Eg- + , * , /, etc.OPERAND: It is the value on which the operato
12 min read
Comparison Operators in Python
The Python operators can be used with various data types, including numbers, strings, booleans, and more. In Python, comparison operators are used to compare the values of two operands (elements being compared). When comparing strings, the comparison is based on the alphabetical order of their characters (lexicographic order).Be cautious when compa
5 min read
Python Membership and Identity Operators
There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators. Table of Content Python Membership OperatorsPython IN Oper
7 min read
Python Bitwise Operators
Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value the operator operates on is known as the Operand.  Python Bitwise OperatorsPython bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into
6 min read
Division Operators in Python
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. Division Operators in PythonThere are two types of division operators: Float divisionInteger division( Floor division)When an integer is divided, the
6 min read
Python Logical Operators
Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions. These Python operators, alongside arithmetic operators, are special symbols used to carry out computations on values and variables. In this article, we will discuss logical operators in Python definition and also loo
6 min read
Python Arithmetic Operators
The Python operators are fundamental for performing mathematical calculations in programming languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform mathematical operations on numerical values. In most programming languages, arithmetic operators include addition (+), subtraction (-), multiplication (*), d
5 min read
Why Are There No ++ and -- Operators in Python?
Python does not include the ++ and -- operators that are common in languages like C, C++, and Java. This design choice aligns with Python's focus on simplicity, clarity, and reducing potential confusion. In this article, we will see why Python does not include these operators and how you can achieve similar functionality using Pythonic alternatives
3 min read
Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. For example, 10 + 20 * 30 is calculated as 10 + (20 *
3 min read
Boolean Operators - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
5 min read
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean. Logical Not (or !) Operator in PythonIn Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True i
4 min read
SQL Operators
SQL Operators perform arithmetic, comparison, and logical operations to manipulate and retrieve data from databases. In this article, we will discuss Operators in SQL with examples, and understand how they work in SQL. Operators in SQLOperators in SQL are symbols that help us to perform specific mathematical and logical computations on operands. An
5 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Article Tags :
Practice Tags :