• Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Python Operators
  • Precedence and Associativity of Operators in Python
  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic
  • Ternary Operator in Python
  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

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 .

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.

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.

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Please Login to comment...

Similar reads.

author

  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Tutorial

  • Python Basics
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators

Python - Assignment Operators

  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python Control Statements
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Object & Classes
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Built-in Exceptions
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - GUIs
  • Python Questions and Answers
  • Python Useful Resources
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python Assignment Operator

The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

Example of Assignment Operator in Python

Consider following Python statements −

At the first instance, at least for somebody new to programming but who knows maths, the statement "a=a+b" looks strange. How could a be equal to "a+b"? However, it needs to be reemphasized that the = symbol is an assignment operator here and not used to show the equality of LHS and RHS.

Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.

In the statement "a+=b", the two operators "+" and "=" can be combined in a "+=" operator. It is called as add and assign operator. In a single statement, it performs addition of two operands "a" and "b", and result is assigned to operand on left, i.e., "a".

Augmented Assignment Operators in Python

In addition to the simple assignment operator, Python provides few more assignment operators for advanced use. They are called cumulative or augmented assignment operators. In this chapter, we shall learn to use augmented assignment operators defined in Python.

Python has the augmented assignment operators for all arithmetic and comparison operators.

Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands may be of different types. However, the type of left operand changes to the operand of on right, if it is wider.

The += operator is an augmented operator. It is also called cumulative addition operator, as it adds "b" in "a" and assigns the result back to a variable.

The following are the augmented assignment operators in Python:

  • Augmented Addition Operator
  • Augmented Subtraction Operator
  • Augmented Multiplication Operator
  • Augmented Division Operator
  • Augmented Modulus Operator
  • Augmented Exponent Operator
  • Augmented Floor division Operator

Augmented Addition Operator (+=)

Following examples will help in understanding how the "+=" operator works −

It will produce the following output −

Augmented Subtraction Operator (-=)

Use -= symbol to perform subtract and assign operations in a single statement. The "a-=b" statement performs "a=a-b" assignment. Operands may be of any number type. Python performs implicit type casting on the object which is narrower in size.

Augmented Multiplication Operator (*=)

The "*=" operator works on similar principle. "a*=b" performs multiply and assign operations, and is equivalent to "a=a*b". In case of augmented multiplication of two complex numbers, the rule of multiplication as discussed in the previous chapter is applicable.

Augmented Division Operator (/=)

The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is equivalent to "a=a/b". The division operation of int or float operands is float. Division of two complex numbers returns a complex number. Given below are examples of augmented division operator.

Augmented Modulus Operator (%=)

To perform modulus and assignment operation in a single statement, use the %= operator. Like the mod operator, its augmented version also is not supported for complex number.

Augmented Exponent Operator (**=)

The "**=" operator results in computation of "a" raised to "b", and assigning the value back to "a". Given below are some examples −

Augmented Floor division Operator (//=)

For performing floor division and assignment in a single statement, use the "//=" operator. "a//=b" is equivalent to "a=a//b". This operator cannot be used with complex numbers.

To Continue Learning Please Login

Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise

Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and returns a sum of two operands as a result.

Python includes the operator module that includes underlying methods for each operator. For example, the + operator calls the operator.add(a,b) method.

Above, expression 5 + 6 is equivalent to the expression operator.add(5, 6) and operator.__add__(5, 6) . Many function names are those used for special methods, without the double underscores (dunder methods). For backward compatibility, many of these have functions with the double underscores kept.

Python includes the following categories of operators:

Arithmetic Operators

Assignment operators, comparison operators, logical operators, identity operators, membership test operators, bitwise operators.

Arithmetic operators perform the common mathematical operation on the numeric operands.

The arithmetic operators return the type of result depends on the type of operands, as below.

  • If either operand is a complex number, the result is converted to complex;
  • If either operand is a floating point number, the result is converted to floating point;
  • If both operands are integers, then the result is an integer and no conversion is needed.

The following table lists all the arithmetic operators in Python:

The assignment operators are used to assign values to variables. The following table lists all the arithmetic operators in Python:

The comparison operators compare two operands and return a boolean either True or False. The following table lists comparison operators in Python.

The logical operators are used to combine two boolean expressions. The logical operations are generally applicable to all objects, and support truth tests, identity tests, and boolean operations.

The identity operators check whether the two objects have the same id value e.i. both the objects point to the same memory location.

The membership test operators in and not in test whether the sequence has a given item or not. For the string and bytes types, x in y is True if and only if x is a substring of y .

Bitwise operators perform operations on binary operands.

  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

python assignment operators explained

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • Python Questions & Answers
  • Python Skill Test
  • Python Latest Articles

Python Assignment Operators

Lesson Contents

Python assignment operators are one of the operator types and assign values to variables . We use arithmetic operators here in combination with a variable.

Let’s take a look at some examples.

Operator Assignment (=)

This is the most basic assignment operator and we used it before in the lessons about lists , tuples , and dictionaries .  For example, we can assign a value (integer) to a variable:

Operator Addition (+=)

We can add a number to our variable like this:

Using the above operator is the same as doing this:

The += operator is shorter to write but the end result is the same.

Operator Subtraction (-=)

We can also subtract a value. For example:

Using this operator is the same as doing this:

Operator Multiplication (*=)

We can also use multiplication. We’ll multiply our variable by 4:

Which is similar to:

Operator Division (/=)

Let’s try the divide operator:

This is the same as:

Operator Modulus (%=)

We can also calculate the modulus. How about this:

This is the same as doing it like this:

Operator Exponentiation (**=)

How about exponentiation? Let’s give it a try:

Which is the same as doing it like this:

Operator Floor Division (//=)

The last one, floor division:

You have now learned how to use the Python assignment operators to assign values to variables and how you can use them with arithmetic operators . I hope you enjoyed this lesson. If you have any questions, please leave a comment.

Ask a question or start a discussion by visiting our Community Forum

logo

Python Assignment Operators

In Python, an assignment operator is used to assign a value to a variable. The assignment operator is a single equals sign (=). Here is an example of using the assignment operator to assign a value to a variable:

In this example, the variable x is assigned the value 5.

There are also several compound assignment operators in Python, which are used to perform an operation and assign the result to a variable in a single step. These operators include:

  • +=: adds the right operand to the left operand and assigns the result to the left operand
  • -=: subtracts the right operand from the left operand and assigns the result to the left operand
  • *=: multiplies the left operand by the right operand and assigns the result to the left operand
  • /=: divides the left operand by the right operand and assigns the result to the left operand
  • %=: calculates the remainder of the left operand divided by the right operand and assigns the result to the left operand
  • //=: divides the left operand by the right operand and assigns the result as an integer to the left operand
  • **=: raises the left operand to the power of the right operand and assigns the result to the left operand

Here are some examples of using compound assignment operators:

Assignment Operators

This lesson showcases Python's various assignment operators and their purpose.

Assigning Values

  • The Other Operators

This is a category of operators which is used to assign values to a variable. The = operator is an assignment operator, but not the only one.

Here’s a list of all the assignment operators supported in Python:

Let’s go through a few examples to see how values are assigned to variables.

Variables are mutable , so we can change their values whenever we want!

Get hands-on with 1200+ tech skills courses.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output

Python Operators

Python flow control.

Python if...else Statement

  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers, Type Conversion and Mathematics
  • Python List
  • Python Tuple
  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python

Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

Precedence and Associativity of Operators in Python

  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python 3 Tutorial

  • Python Strings
  • Python any()

Operators are special symbols that perform operations on variables and values. For example,

Here, + is an operator that adds two numbers: 5 and 6 .

  • Types of Python Operators

Here's a list of different types of Python operators that we will learn in this tutorial.

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,

Here, - is an arithmetic operator that subtracts two values or variables.

Example 1: Arithmetic Operators in Python

In the above example, we have used multiple arithmetic operators,

  • + to add a and b
  • - to subtract b from a
  • * to multiply a and b
  • / to divide a by b
  • // to floor divide a by b
  • % to get the remainder
  • ** to get a to the power b

2. Python Assignment Operators

Assignment operators are used to assign values to variables. For example,

Here, = is an assignment operator that assigns 5 to x .

Here's a list of different assignment operators available in Python.

Example 2: Assignment Operators

Here, we have used the += operator to assign the sum of a and b to a .

Similarly, we can use any other assignment operators as per our needs.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False . For example,

Here, the > comparison operator is used to compare whether a is greater than b or not.

Example 3: Comparison Operators

Note: Comparison operators are used in decision-making and loops . We'll discuss more of the comparison operator and decision-making in later tutorials.

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False . They are used in decision-making. For example,

Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .

Example 4: Logical Operators

Note : Here is the truth table for these logical operators.

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111 .

In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)

6. Python Special operators

Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.

  • Identity operators

In Python, is and is not are used to check if two values are located at the same memory location.

It's important to note that having two variables with equal values doesn't necessarily mean they are identical.

Example 4: Identity operators in Python

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.

  • Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).

In a dictionary, we can only test for the presence of a key, not the value.

Example 5: Membership operators in Python

Here, 'H' is in message , but 'hello' is not present in message (remember, Python is case-sensitive).

Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .

  • Precedence and Associativity of operators in Python

Table of Contents

  • Introduction
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python Bitwise operators
  • Python Special operators

Video: Operators in Python

Sorry about that.

Related Tutorials

Python Tutorial

Currently Reading :

Currently reading:

Simple assignment operator in Python

Different assignment operators in python.

Rajat Gupta

Software Developer

Published on  Thu Jun 30 2022

Assignment operators in Python are in-fix which are used to perform operations on variables or operands and assign values to the operand on the left side of the operator. It performs arithmetic, logical, and bitwise computations.

Assignment Operators in Python

Add and equal operator, subtract and equal operator, multiply and equal operator, divide and equal operator, modulus and equal operator, double divide and equal operator, exponent assign operator.

  • Bitwise and operator

Bitwise OR operator

  • Bitwise XOR Assignment operator

Bitwise right shift assignment operator

Bitwise left shift assignment operator.

The Simple assignment operator in Python is denoted by = and is used to assign values from the right side of the operator to the value on the left side.

This operator adds the value on the right side to the value on the left side and stores the result in the operand on the left side.

This operator subtracts the value on the right side from the value on the left side and stores the result in the operand on the left side.

The Multiply and equal operator multiplies the right operand with the left operand and then stores the result in the left operand.

It divides the left operand with the right operand and then stores the quotient in the left operand.

The modulus and equal operator finds the modulus from the left and right operand and stores the final result in the left operand.

The double divide and equal or the divide floor and equal operator divides the left operand with the right operand and stores the floor result in the left operand.

It performs exponential or power calculation and assigns value to the left operand.

Bitwise And operator

Performs Bitwise And operation on both variables and stores the result in the left operand. The Bitwise And operation compares the corresponding bits of the left operand to the bits of the right operand and if both bits are 1, the corresponding result is also 1 otherwise 0.

The binary value of 3 is 0011 and the binary value of 5 is 0101, so when the Bitwise And operation is performed on both the values, we get 0111, which is 7 in decimal.

Performs Bitwise OR operator on both variables and stores the result in the left operand. The Bitwise OR operation compares the corresponding bits of the left operand to the bits of the right operand and if any one of the bit is 1, the corresponding result is also 1 otherwise 0.

The binary value of 5 is 0101 and the binary value of 10 is 1010, so when the Bitwise OR operation is performed on both the values, we get 1111, which is 15 in decimal .

Bitwise XOR operator

Performs Bitwise XOR operator on both variables and stores the result in the left operand. The Bitwise XOR operation compares the corresponding bits of the left operand to the bits of the right operand and if only one of the bit is 1, the corresponding result is also 1 otherwise 0.

The binary value of 5 is 0101 and the binary value of 9 is 1001, so when the Bitwise XOR operation is performed on both the values, we get 1100, which is 12 in decimal.

This operator performs a Bitwise right shift on the operands and stores the result in the left operand.

The binary value of 15 is 1111, so when the Bitwise right shift operation is performed on ‘a’, we get 0011, which is 3 in decimal.

This operator performs a Bitwise left shift on the operands and stores the result in the left operand.

The binary value of 15 is 1111, so when the Bitwise right shift operation is performed on ‘a’, we get 00011110, which is 30 in decimal.

Closing Thoughts

In this tutorial, we read about different types of assignment operators in Python which are special symbols used to perform arithmetic, logical and bitwise operations on the operands and store the result in the left side operand. One can read about other Python concepts here .

About the author

Rajat Gupta is an experienced financial analyst known for his deep insights into market trends and investment strategies. He excels in providing robust financial solutions that drive growth and stability.

Related Blogs

List of Lists in Python

Methods to check if a python string contains a substring

Ancil Eric D'Silva

Convert String to List in Python

How to represent an infinite number in Python?

How to square numbers in Python?

List Index Out of Range – Python Error [Solved]

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your project.

  • Programmers
  • React Native
  • Ruby on Rails

Welcome! This site is currently in beta. Get 10% off everything with promo code BETA10.

Python Assignment Operator

  • Introduction

Chained Assignment

Shorthand assignment, shorthand assignment operators, playground: assignment operator practice, assignment methods.

All assignment operators are used to assign values to variables. Wait, is there more than one assignment operator? Yes, but they're all quite similar to the ones you've seen. You've used the most common assignment operator, and its symbol is a single equals sign ( = ).

For example, to assign x the value of 10 you type the following:

Different Assignment Methods

You have used this assignment statement before to assign values to variables. Apart from this very common way of using it, a few other situations use the same symbol for slightly different assignments.

You can assign the same value to multiple variables in one swoop by using an assignment chain:

This construct assigns 10 to x , y , and z . Using the chained assignment statement in Python is rare, but if you see it around, now you know what that's about.

Shorthand assignments, on the other hand, are a common occurrence in Python code. This is where the other assignment operators come into play. Shorthand assignments make writing code more efficient and can improve readability---at least once you know about them!

For example, think of a situation where you have a variable x and you want to add 1 to that variable:

This works well and is perfectly fine Python code. However, there is a more concise way of writing the same code using shorthand assignment :

Check out how the second line in these two code snippets is different. You don't need to write the name of the variable x a second time using the shorthand operator += like in the example above.

Both code examples shown achieve the exact same result and are equivalent. The shorthand assignment allows you to use less code to complete the task.

Python comes with a couple of shorthand assignment operators. Some of the most common ones include the following:

These operators are combinations of familiar arithmetic operators with the assignment operator ( = ). You have already used some of Python's arithmetic operators, and you'll learn more about them in the upcoming lesson.

Play around and combine different operators you can think of with the assignment operator below.

  • Which ones work and do what you expect them to?
  • Which ones don't?

Summary: Python Assignment Operator

  • Assignment operators are used to assign values to variables
  • Shorthand assignment is the most commonly used in Python
  • The table summarizing the assignment operators is provided in the lesson
  • Chain Assignment : A method used to assign multiple variables at one
  • Shorthand Assignment : A series of short forms for manipulating data

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in python.

' src=

Last Updated on June 8, 2023 by Prepbytes

python assignment operators explained

To fully comprehend the assignment operators in Python, it is important to have a basic understanding of what operators are. Operators are utilized to carry out a variety of operations, including mathematical, bitwise, and logical operations, among others, by connecting operands. Operands are the values that are acted upon by operators. In Python, the assignment operator is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is the most commonly used operator in Python. In this article, we will explore the assignment operator in Python, how it works, and its different types.

What is an Assignment Operator in Python?

The assignment operator in Python is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is used to assign a value to a variable. When an assignment operator is used, the value on the right-hand side is assigned to the variable on the left-hand side. This is a fundamental operation in programming, as it allows developers to store data in variables that can be used throughout their code.

For example, consider the following line of code:

Explanation: In this case, the value 10 is assigned to the variable a using the assignment operator. The variable a now holds the value 10, and this value can be used in other parts of the code. This simple example illustrates the basic usage and importance of assignment operators in Python programming.

Types of Assignment Operator in Python

There are several types of assignment operator in Python that are used to perform different operations. Let’s explore each type of assignment operator in Python in detail with the help of some code examples.

1. Simple Assignment Operator (=)

The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is:

Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example

Explanation: In this case, the value 25 is assigned to the variable a using the simple assignment operator. The variable a now holds the value 25.

2. Addition Assignment Operator (+=)

The addition assignment operator is used to add a value to a variable and store the result in the same variable. The syntax for the addition assignment operator is:

Here, the value on the right-hand side is added to the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is incremented by 5 using the addition assignment operator. The result, 15, is then printed to the console.

3. Subtraction Assignment Operator (-=)

The subtraction assignment operator is used to subtract a value from a variable and store the result in the same variable. The syntax for the subtraction assignment operator is

Here, the value on the right-hand side is subtracted from the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is decremented by 5 using the subtraction assignment operator. The result, 5, is then printed to the console.

4. Multiplication Assignment Operator (*=)

The multiplication assignment operator is used to multiply a variable by a value and store the result in the same variable. The syntax for the multiplication assignment operator is:

Here, the value on the right-hand side is multiplied by the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is multiplied by 5 using the multiplication assignment operator. The result, 50, is then printed to the console.

5. Division Assignment Operator (/=)

The division assignment operator is used to divide a variable by a value and store the result in the same variable. The syntax for the division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 5 using the division assignment operator. The result, 2.0, is then printed to the console.

6. Modulus Assignment Operator (%=)

The modulus assignment operator is used to find the remainder of the division of a variable by a value and store the result in the same variable. The syntax for the modulus assignment operator is

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the remainder is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the modulus assignment operator. The remainder, 1, is then printed to the console.

7. Floor Division Assignment Operator (//=)

The floor division assignment operator is used to divide a variable by a value and round the result down to the nearest integer, and store the result in the same variable. The syntax for the floor division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is rounded down to the nearest integer. The rounded result is then stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the floor division assignment operator. The result, 3, is then printed to the console.

8. Exponentiation Assignment Operator (**=)

The exponentiation assignment operator is used to raise a variable to the power of a value and store the result in the same variable. The syntax for the exponentiation assignment operator is:

Here, the variable on the left-hand side is raised to the power of the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is raised to the power of 3 using the exponentiation assignment operator. The result, 8, is then printed to the console.

9. Bitwise AND Assignment Operator (&=)

The bitwise AND assignment operator is used to perform a bitwise AND operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise AND assignment operator is:

Here, the variable on the left-hand side is ANDed with the value on the right-hand side using the bitwise AND operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ANDed with 3 using the bitwise AND assignment operator. The result, 2, is then printed to the console.

10. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator is used to perform a bitwise OR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise OR assignment operator is:

Here, the variable on the left-hand side is ORed with the value on the right-hand side using the bitwise OR operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ORed with 3 using the bitwise OR assignment operator. The result, 7, is then printed to the console.

11. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator is used to perform a bitwise XOR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise XOR assignment operator is:

Here, the variable on the left-hand side is XORed with the value on the right-hand side using the bitwise XOR operator, and the result are stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is XORed with 3 using the bitwise XOR assignment operator. The result, 5, is then printed to the console.

12. Bitwise Right Shift Assignment Operator (>>=)

The bitwise right shift assignment operator is used to shift the bits of a variable to the right by a specified number of positions, and store the result in the same variable. The syntax for the bitwise right shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the right by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is shifted 2 positions to the right using the bitwise right shift assignment operator. The result, 2, is then printed to the console.

13. Bitwise Left Shift Assignment Operator (<<=)

The bitwise left shift assignment operator is used to shift the bits of a variable to the left by a specified number of positions, and store the result in the same variable. The syntax for the bitwise left shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the left by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Conclusion Assignment operator in Python is used to assign values to variables, and it comes in different types. The simple assignment operator (=) assigns a value to a variable. The augmented assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=) perform a specified operation and assign the result to the same variable in one step. The modulus assignment operator (%) calculates the remainder of a division operation and assigns the result to the same variable. The bitwise assignment operators (&=, |=, ^=, >>=, <<=) perform bitwise operations and assign the result to the same variable. The bitwise right shift assignment operator (>>=) shifts the bits of a variable to the right by a specified number of positions and stores the result in the same variable. The bitwise left shift assignment operator (<<=) shifts the bits of a variable to the left by a specified number of positions and stores the result in the same variable. These operators are useful in simplifying and shortening code that involves assigning and manipulating values in a single step.

Here are some Frequently Asked Questions on Assignment Operator in Python:

Q1 – Can I use the assignment operator to assign multiple values to multiple variables at once? Ans – Yes, you can use the assignment operator to assign multiple values to multiple variables at once, separated by commas. For example, "x, y, z = 1, 2, 3" would assign the value 1 to x, 2 to y, and 3 to z.

Q2 – Is it possible to chain assignment operators in Python? Ans – Yes, you can chain assignment operators in Python to perform multiple operations in one line of code. For example, "x = y = z = 1" would assign the value 1 to all three variables.

Q3 – How do I perform a conditional assignment in Python? Ans – To perform a conditional assignment in Python, you can use the ternary operator. For example, "x = a (if a > b) else b" would assign the value of a to x if a is greater than b, otherwise it would assign the value of b to x.

Q4 – What happens if I use an undefined variable in an assignment operation in Python? Ans – If you use an undefined variable in an assignment operation in Python, you will get a NameError. Make sure you have defined the variable before trying to assign a value to it.

Q5 – Can I use assignment operators with non-numeric data types in Python? Ans – Yes, you can use assignment operators with non-numeric data types in Python, such as strings or lists. For example, "my_list += [4, 5, 6]" would append the values 4, 5, and 6 to the end of the list named my_list.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.

Python Operators Explained in Detail with Examples

January 9, 2024

When diving into the world of Python programming, understanding Python operators is akin to learning the alphabets of a new language. These operators act as the building blocks for any Python script, playing a critical role in carrying out operations like arithmetic calculations, comparisons, and logical decisions. Not only do they facilitate code execution, but they also make your code more efficient and readable. In this comprehensive guide, we will explore various types of Python operators, how they function, and why they are essential for anyone aspiring to master Python programming.

Different Python Operators

Here are the list of Python Operators:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Augmented Operators
  • Bitwise Operators
  • Identity Operators
  • Membership Operators

We will cover these in detail in next chapters.

1. Arithmetic operators in Python

As the name suggests, these operators perform various arithmetic operations and calculations like addition, multiplications, division, etc. They can be used with numerical data types like integers and floats, and some can even be used with strings and lists for operations like concatenation and repetition.

Below is a table that provides a detailed explanation of arithmetic operators in Python.

In each example, the variable a is used to store the result of the operation, and then print(a) is used to display the output.

2. Comparison operators in Python

Comparison operators are also known as rational operators as well. They are used to compare different values.  They evaluate different types of expressions and manipulate the values of variables by performing different operations on them.

In each code example, the variable a is used to store the result of the comparison operation, and then print(a) is used to display the Boolean output ( True or False ).

3. Logical operators in Python

Python logical operators are used to evaluate the one or more than one condition between variables or operands by providing specific results. i.e True and False . Useful for making decisions in code (conditionals) and testing multiple conditions . It can be used with any data types that can be converted to Boolean values.

In each example, the variable a is used to store the result of the logical operation, and print(a) is used to display the resulting Boolean value ( True or False ).

4. Assignment Operators

Assignment operators are primarily used to assign values to variables. They perform a single function of assigning a value from the right-hand side to the variable on the left-hand side. It is useful for initializing variables and updating their values.

Below is a table that explains the assignment operators in Python, along with code examples using a small variable name ( a ) and the print() statement to display the result.

In each example, the variable a is initially assigned a value. Then, an assignment operator modifies this value, and print(a) displays the updated value.

5. Augmented Operators (Compound Assignment Operators)

Python has a set of operators known as "augmented assignment operators," also sometimes called "compound assignment operators." These operators provide a shorthand way to apply an operation and an assignment in a single step. They are similar to assignment operators but perform an additional operation before the assignment.

Unlike normal assignment operators, Augmented Assignment Operators are used to replace those statements where a binary operator takes two operands, variable1 and variable1 and then assigns a final result back to one of the operands.

Below is a table that outlines the augmented assignment operators in Python, complete with code examples using a small variable name ( a ) and the print() function to display the result.

In each example, the variable a is initially assigned a value. Then, an augmented assignment operator modifies this value, and print(a) displays the updated value.

6. Bitwise Operators

Bitwise operators in Python are used to operate at a binary level. This means they look directly at the binary digits or binary bits of an integer. Below is a table that explains each bitwise operator in Python, along with a code example that uses a small variable name ( a ) and the print() statement to display the result.

Below are some examples to help you understand how these operators work in Python:

Bitwise AND ( & ): This operator compares each binary digit of the first operand to the corresponding binary digit of the second operand. If both digits are 1 , the digit in the resulting binary representation is 1 , otherwise 0 .

Bitwise OR ( | ):  This operator also compares each binary digit of the first operand to the corresponding binary digit of the second operand. If either of the digits is 1 , the resulting binary digit is 1 .

Bitwise XOR ( ^ ):  The XOR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1 , the corresponding result bit is set to 1 .

Bitwise NOT ( ~ ):  This operator is a unary operator, meaning it works with a single operand. Bitwise NOT will invert the number's bit-wise representation. Note that because Python uses signed integers , the result will be the two's complement of the inverted bits.

Left Shift ( << ):  The left shift operator shifts the bits of a number to the left by a specified number of positions. Each left shift doubles the number, as it is equivalent to multiplication by 2 to the power of the number of shifted positions.

Right Shift ( >> ):  The right shift operator shifts the bits of a number to the right by a specified number of positions. Each right shift halves the number, rounding down.

7. Identity Operators

Identity operators in Python are used to compare the memory locations of two objects. They help to check if two variables refer to the same object in memory. Below is a table that describes the identity operators, accompanied by Python code examples using small variable names ( a and b ) and the print() function to display the result.

Description and Use-cases

is Operator : The is operator checks whether both the operands refer to the same object (i.e., point to the same memory location). It's often used to test if a variable is None , although it can also be used for other objects like lists or dictionaries to ensure that two variables point to the same data structure.

is not Operator : The is not operator is essentially the opposite of the is operator. It checks whether two variables refer to different objects in memory. This is useful for ensuring that two variables don't share the same underlying data.

Remember, is and is not operators should not be confused with == and != operators. The former compare the memory locations, whereas the latter compare the values.

8. Membership Operators

Membership operators are used to test whether a value is a member of a sequence such as a list, tuple, or string, or a collection like a dictionary . Below is a table explaining the membership operators in Python, with code examples using small variable names ( a and b ) and the print() statement to display the result.

in Operator : The in operator is used to check if a value exists in a sequence or a collection. It's a quick way to check for the presence of a specific item.

not in Operator : The not in operator is essentially the opposite of the in operator. It checks if a specified element is not present in a given sequence or collection.

Assignment Vs Augmented Assignment Operators

The fundamental difference between assignment operators and augmented assignment operators lies in their functionality and readability.

Assignment Operators:

Basic Function : Assignment operators are mainly used to assign values to variables.

Single Operation : Assignment operators perform just one function: they assign the value on the right-hand side to the variable on the left-hand side.

Multiple Steps for Operations : If you need to perform an operation (like addition, subtraction, etc.) and then assign the result to the variable, you have to do it in multiple steps or lines.

Augmented Assignment Operators:

Enhanced Function : Augmented assignment operators perform an operation in addition to assignment, effectively combining the two into a single action.

Conciseness : They allow for more concise code. Instead of writing a = a + 2 , you can simply write a += 2 .

Efficiency : Augmented assignment operators may be more efficient in some cases, as they can reduce the amount of typing and potentially perform the operation faster, although the speed difference is generally negligible for basic types.

Multiple Operations : They make it easier to perform complex calculations and reassignments in a single step.

Operators precedence order in Python

Operator precedence in Python determines the order in which operators are evaluated when multiple operators are present in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Here is a list of operators in Python , sorted from highest precedence to lowest:

  • Parentheses () : Expressions inside parentheses are evaluated first.
  • Exponentiation ** : Right-to-left associativity.
  • Complement, Unary Plus and Minus ~ + - : Unary operators.
  • Multiply, Divide, Floor Divide, and Modulus * / // % : Left-to-right associativity.
  • Addition and Subtraction + - : Left-to-right associativity.
  • Bitwise Right Shift and Left Shift >> << : Left-to-right associativity.
  • Bitwise AND & : Left-to-right associativity.
  • Bitwise XOR ^ : Left-to-right associativity.
  • Bitwise OR | : Left-to-right associativity.
  • Comparison Operators == != < <= > >= : Left-to-right associativity.
  • Identity Operators is is not : Left-to-right associativity.
  • Membership Operators in not in : Left-to-right associativity.
  • Logical NOT not : Right-to-left associativity.
  • Logical AND and : Left-to-right associativity.
  • Logical OR or : Left-to-right associativity.
  • Conditional Expression if else : Right-to-left associativity.
  • Assignment = : Right-to-left associativity.
  • Augmented Assignment += -= *= /= //= %= **= &= ^= |= <<= >>= : Right-to-left associativity.

When multiple operators have the same precedence, Python usually evaluates them from left to right (left-to-right associativity). The exception to this rule is the exponentiation operator ( ** ), which has right-to-left associativity, meaning that operations are evaluated from right to left.

For example:

  • With the expression 3 + 4 * 2 , the multiplication ( * ) operator has higher precedence than addition ( + ), so 4 * 2 is evaluated first, resulting in 3 + 8 which is 11 .
  • In the expression 2 ** 3 ** 2 , the ** operator is right associative, so 3 ** 2 is evaluated first, resulting in 2 ** 9 which is 512

Special Cases and Syntax

Python allows some operators to be used in unconventional ways. For example, you can use the * operator to repeat strings and lists.

While using operators, you should follow certain syntax rules, like putting them between operands (in infix notation), or ensuring that they are applied to compatible data types.

Chaining : Python allows you to chain multiple comparisons to perform a more complex test.

Chained comparisons also benefit from short-circuit behavior. This means that if one comparison fails, the remaining ones are not executed, which can improve performance.

Mixing Operators in Expressions: Python allows for mixing certain types of operators, but it's important to use parentheses to make the expression clear.

When mixing operators with different data types, Python will usually automatically convert the types to make them compatible, if possible.

Common Mistakes and Best Practices

Importance of parentheses.

Clarifying Ambiguity : Parentheses help in making the expression unambiguous. This is especially crucial when dealing with operators of different precedences.

Parentheses can also make complex expressions more readable, even if they're not strictly necessary.

Floating-Point Arithmetic Caveats

Precision : Floating-point numbers do not always represent decimal numbers precisely, which can lead to errors in calculations.

Integer Division : When dividing integers, use // for integer division and / for floating-point division to avoid unexpected results.

Common Pitfalls with Assignment Operators

Immutable Reassignment : Be cautious when you are working with immutable types like tuples or strings. Reassignment will produce a new object instead of modifying the original one.

Augmented Assignment : Remember that augmented assignment ( += , *= etc.) can behave differently for mutable and immutable objects.

Chaining Assignments : While Python allows for chained assignments like a = b = 1 , be cautious when using this feature with mutable objects as it can lead to unexpected behavior.

Practical Examples

How to use Arithmetic Operators in Math Calculations

Arithmetic operators come in handy for a wide range of math calculations. Here we are calculating Area and Perimeter:

Using Comparison Operators in Conditional Statements

Comparison operators are frequently used in conditional statements like if , elif , and else . Here we are determining the Largest Number:

Using Logical Operators in Decision Making

Logical operators can be used for making complex decisions. Here we are checking the eligibility for a Loan:

Real-world Scenarios where Bitwise Operators are Useful

Bitwise operators are particularly useful in low-level programming and bit manipulation:

Setting Flags

Checking Flags

How Membership and Identity Operators Work in Data Structures like Lists, Sets, and Dictionaries

Membership and identity operators are quite useful when working with data structures:

Dictionaries

Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.  Moreover, we also covered the precedence of these operators over each other.

Further Reading

Python operators Augmented operators More about python operators

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

Save my name and email in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

python assignment operators explained

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Recent Comments

Popular posts, 7 tools to detect memory leaks with examples, 100+ linux commands cheat sheet & examples, tutorial: beginners guide on linux memory management, top 15 tools to monitor disk io performance with examples, overview on different disk types and disk interface types, 6 ssh authentication methods to secure connection (sshd_config), how to check security updates list & perform linux patch management rhel 6/7/8, 8 ways to prevent brute force ssh attacks in linux (centos/rhel 7).

Privacy Policy

HTML Sitemap

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Python Assignment Operators

Assignment operators are used to assign values to variables:

Advertisement

Python Comparison Operators

Comparison operators are used to compare two values:

Python Logical Operators

Logical operators are used to combine conditional statements:

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Precedence

Operator precedence describes the order in which operations are performed.

Parentheses has the highest precedence, meaning that expressions inside parentheses must be evaluated first:

Multiplication * has higher precedence than addition + , and therefor multiplications are evaluated before additions:

The precedence order is described in the table below, starting with the highest precedence at the top:

If two operators have the same precedence, the expression is evaluated from left to right.

Addition + and subtraction - has the same precedence, and therefor we evaluate the expression from left to right:

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

CloneCoding Cover Image

  • Tips & Tutorial

[Python] Assignment Operators with Examples Explained

CloneCoding

  • Language / Python
  • August 26, 2023

Assignment operators in Python are tools, enabling developers to assign values to variables efficiently. Beyond the basic assignment (=), Python also provides a suite of compound assignment operators that combine arithmetic operations with assignment, streamlining code and enhancing readability.

The Basic Assignment Operator (=)

The basic assignment operator in Python is = . It's used to assign a value to a variable. When you use this operator, the value on the right side of the = is assigned to the variable on the left side. It's essential to differentiate between the assignment operator ( = ) and the equality operator ( == ) in Python. The former assigns a value, whereas the latter checks for equality.

Compound Assignment Operators

Compound assignment operators are a combination of basic arithmetic or bitwise operators with the basic assignment operator. They perform a specific operation on the variable's current value and then assign the result back to the same variable. This eliminates the need to mention the variable name twice, making the code concise and more readable.

Addition Assignment (+=)

The addition assignment operator ( += ) increments the value of a variable by a specified value. Instead of writing x = x + 3 , you can simply write x += 3 , which will add 3 to the current value of x .

Subtraction Assignment (-=)

The subtraction assignment operator ( -= ) decrements the variable's value by the specified value. Instead of writing x = x - 4 , you can use x -= 4 , which will subtract 4 from the current value of x .

Multiplication Assignment (*=)

The multiplication assignment operator ( *= ) multiplies the variable's current value by a specified number. It's a more concise way of writing operations like x = x * 2 . Instead, you can write x *= 2 .

Division Assignment (/=)

The division assignment operator ( /= ) divides the variable's current value by the given number and assigns the result back to the variable. So, x /= 4 is equivalent to x = x / 4 .

Modulus Assignment (%=)

The modulus assignment operator ( %= ) calculates the remainder of the division of the variable by the given number and assigns this remainder back to the variable. For instance, if you want to store the remainder of x divided by 4, you'd use x %= 4 .

Exponentiation Assignment (**=)

The exponentiation assignment operator ( **= ) raises the variable's current value to the power of a specified number. It's a shorthand for operations like x = x ** 2 , which can instead be written as x **= 2 .

Floor Division Assignment (//=)

The floor division assignment operator ( //= ) divides the variable's value by the given number, rounds down the result to the nearest whole number, and then assigns this value back to the variable. Thus, x //= 3 is a more concise way of expressing x = x // 3 .

Advantages of Using Compound Assignment Operators

The primary advantage of using compound assignment operators is to reduce the amount of code and enhance clarity. They offer a more concise way to perform operations and assignments simultaneously.

It's important to note that not all assignment operators are applicable to all data types. Some of them, when used with non-compatible types, will result in TypeErrors or other exceptions. As seen in the examples, addition assignment works with numbers, strings, and lists, but subtraction assignment only works with numbers. It's crucial to understand and test the behavior of each operator with various data types to avoid unexpected errors in your code.

  • Compound assignment operators combine an arithmetic operation with assignment. Examples include += , -= , and *= .
  • These operators are safe to use but understanding their functionality is crucial to avoid unexpected outcomes.
  • While primarily used with numbers, certain operators can also be applied to other data types like strings and lists.
  • The basic assignment operator ( = ) assigns a value to a variable. Compound assignment operators perform an operation and assignment in a single step.
  • They offer a more concise way to write code, thus enhancing readability and reducing potential errors.

Other Posts in the Language / Python

CloneCoding Logo

Innovation Starts with a Single Line of Code!

  • Python ( 36 )
  • JavaScript ( 12 )
  • React ( 3 )
  • Next.js ( 3 )
  • Node.js ( 4 )
  • TA-Lib ( 7 )
  • Dev Tips ( 4 )

Recent Posts

[JavaScript] Downloading Screenshots using html2canvas

  • / operators

Operators in Python

Getting started.

As your knowledge base in Python grows, you'll gain the ability to manipulate data types and create flexible expressions. Logically, we need operators to perform such actions and sway the functioning of our Python programs as we deem necessary. Simply put, we use operators to perform operations on values, variables, and data structures, called operands, and control the flow of a program. We'll explore the different types of operators available in Python and learn how to properly use them.

Python Arithmetic Operators

You'll likely be familiar with most of these. Just be aware of the symbol used in the rudimentary examples, as we'll be using them in more complex structures later on.

Arithmetic operators are used to performing basic mathematical operations such as addition, subtraction, multiplication, and division. They are used to perform calculations and make numerical comparisons.

Python Assignment Operators

We've already explained the use of the equal sign ( = ) in our Basics of Variables in Python and we saw several examples of how we assign values to variables.

You'll notice several shorthand assignment operators, or augmented assignments, allowing us to perform an operation and then assign the result to a variable with a single line of code. So, let's go over them and observe how they neatly store and manipulate values in memory.

Comparison Operators

With comparison operators, we can compare values and variables in Python. They return a Boolean value of either True or False based on the comparison made. Comparison operators are oftentimes used in conditional statements to control the flow of a program.

Bitwise Operators

Bitwise operators perform operations on binary representations of numbers in Python. They are often used for low-level operations, such as setting or checking individual bits within a number.

Logical Operators

We can leverage logical operators to carry out operations on Boolean values in Python. They grant us decision-making based on multiple conditions and control the flow of a program.

Specific Python Operators

In addition to the ones we saw, Python has a few operators that are specific to the language.

  • Identity Operators

Identity operators are used to comparing the memory locations of two objects in Python. They enable us to find out if two objects are the same object in memory, or if they are different objects with the same values.

  • Membership Operators

Membership operators are used to testing if a value or variable is a member of a sequence, such as a list, tuple, or string. With them, we can determine whether an object is present in a sequence.

Python Operator Precedence

Just like in mathematics, operators in Python have a specific order of precedence that determines the order in which operations are performed.

Exponentiation (**)

Complement, unary plus, and minus (e.g. ~x, +x, -x)

Multiplication, division, floor division, and modulus (e.g. *, /, //, %)

Addition and subtraction (e.g. +, -)

Bitwise shift operations (e.g. <<, >>)

Bitwise AND (e.g. &)

Bitwise XOR (e.g. ^)

Bitwise OR (e.g. |)

Comparison operators (e.g. ==, !=, >, <, >=, <=)

Membership operators (e.g. in, not in)

Identity operators (e.g. is, is not)

Logical NOT (e.g. not)

Logical AND (e.g. and)

Logical OR (e.g. or)

Lacking knowledge of the precedence order in Python can affect the outcome of a calculation or comparison. If we're unsure of the order of precedence, it's always a good idea to use parentheses to explicitly define the order of operations.

Final Thoughts

We've delved into the various types of operators available in Python and gained enough information to start experimenting with them. They can be used in a variety of situations, from simple mathematical operations to complex decision-making processes. Once you begin creating beginner projects you'll inevitably find yourself using most of these operators in expressions. Don't hesitate to come back again when you need to refresh your memory. The point of programming isn't to resort to rote learning.

On this page

Notice: While JavaScript is not essential for this website, your interaction with the content will be limited. Please turn JavaScript on for the full experience.

Notice: Your browser is ancient . Please upgrade to a different browser to experience a better web.

  • Chat on IRC
  • >_ Launch Interactive Shell

Functions Defined

The core of extensible programming is defining functions. Python allows mandatory and optional arguments, keyword arguments, and even arbitrary argument lists. More about defining functions in Python 3

Compound Data Types

Lists (known as arrays in other languages) are one of the compound data types that Python understands. Lists can be indexed, sliced and manipulated with other built-in functions. More about lists in Python 3

Intuitive Interpretation

Calculations are simple with Python, and expression syntax is straightforward: the operators + , - , * and / work as expected; parentheses () can be used for grouping. More about simple math functions in Python 3 .

All the Flow You’d Expect

Python knows the usual control flow statements that other languages speak — if , for , while and range — with some of its own twists, of course. More control flow tools in Python 3

Quick & Easy to Learn

Experienced programmers in any other language can pick up Python very quickly, and beginners find the clean syntax and indentation structure easy to learn. Whet your appetite with our Python 3 overview.

Python is a programming language that lets you work quickly and integrate systems more effectively. Learn More

Get Started

Whether you're new to programming or an experienced developer, it's easy to learn and use Python.

Start with our Beginner’s Guide

Python source code and installers are available for download for all versions!

Latest: Python 3.12.3

Documentation for Python's standard library, along with tutorials and guides, are available online.

docs.python.org

Looking for work or have a Python related position that you're trying to hire for? Our relaunched community-run job board is the place to go.

jobs.python.org

Latest News

  • 2024- 05-08 Python 3.13.0 beta 1 released
  • 2024- 05-08 PSF Grants Program 2022 & 2023 Transparency Report
  • 2024- 05-07 PSF Board Election Dates for 2024
  • 2024- 05-03 The PSF's 2023 Annual Impact Report is here!

Upcoming Events

  • 2024- 05-22 PyCon Italia 2024
  • 2024- 05-27 GeoPython 2024
  • 2024- 05-29 csv,conf,v8
  • 2024- 05-29 PyLadies Amsterdam: NLP projects with spaCy
  • 2024- 06-01 Building Python Communities Yaounde

Success Stories

Generating realistic location data for users for testing or modeling simulations is a hard problem. Current approaches just create random locations inside a box, placing users in waterways or on top of buildings. This inability to make accurate, synthetic location data stifles a lot of innovative projects that require diverse and complex datasets to fuel their work.

Use Python for…

  • Web Development : Django , Pyramid , Bottle , Tornado , Flask , web2py
  • GUI Development : tkInter , PyGObject , PyQt , PySide , Kivy , wxPython , DearPyGui
  • Scientific and Numeric : SciPy , Pandas , IPython
  • Software Development : Buildbot , Trac , Roundup
  • System Administration : Ansible , Salt , OpenStack , xonsh

>>> Python Enhancement Proposals (PEPs) : The future of Python is discussed here. RSS

>>> python software foundation.

The mission of the Python Software Foundation is to promote, protect, and advance the Python programming language, and to support and facilitate the growth of a diverse and international community of Python programmers. Learn more

Become a Member Donate to the PSF

IMAGES

  1. #15- Assignment Operators Explained

    python assignment operators explained

  2. Explain operators in python with example

    python assignment operators explained

  3. Assignment Operators

    python assignment operators explained

  4. Python 3 Tutorial

    python assignment operators explained

  5. Python Tutorials: Assignment Operators In python

    python assignment operators explained

  6. 7 Types of Python Operators that will ease your programming

    python assignment operators explained

VIDEO

  1. Assignment

  2. Python Assignment Operators

  3. L-5.4 Assignment Operators

  4. 💥Operators in Python

  5. Python Assignment Operators

  6. PYTHON OPERATORS ASSIGNMENT OPREATORS

COMMENTS

  1. Assignment Operators in Python

    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.

  2. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  3. Python Assignment Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.

  4. Python

    Python Assignment Operator. The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions ...

  5. Operators and Expressions in Python

    Run the operation defined by the operator that prefixes the assignment operator (=), using the current value of variable and the return value of expression as operands. Assign the resulting value back to variable. The table below shows a summary of the augmented operators for arithmetic operations:

  6. Assignment Expressions: The Walrus Operator

    In this lesson, you'll learn about the biggest change in Python 3.8: the introduction of assignment expressions.Assignment expression are written with a new notation (:=).This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.. Assignment expressions allow you to assign and return a value in the same expression.

  7. Python Assignment Operators

    Assignment operators in Python. The above code is useful when we want to update the same number. We can also use two different numbers and use the assignment operators to apply them on two different values. num_one = 6. num_two = 3. print(num_one) num_one += num_two. print(num_one) num_one -= num_two.

  8. Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity

    Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise. Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and ...

  9. Python Assignment Operators

    Operator Multiplication (*=) Operator Division (/=) Operator Modulus (%=) Operator Exponentiation (**=) Operator Floor Division (//=) Conclusion. Python assignment operators are one of the operator types and assign values to variables. We use arithmetic operators here in combination with a variable. Let's take a look at some examples.

  10. Python Assignment Operators

    In Python, an assignment operator is used to assign a value to a variable. The assignment operator is a single equals sign (=). Here is an example of using the assignment operator to assign a value to a variable: x = 5. In this example, the variable x is assigned the value 5. There are also several compound assignment operators in Python, which ...

  11. Assignment Operators

    This is a category of operators which is used to assign values to a variable. The = operator is an assignment operator, but not the only one. Here's a list of all the assignment operators supported in Python: Operator. Purpose. Notation. =. Assign. In-fix.

  12. Python Operators (With Examples)

    Assignment operators are used to assign values to variables. For example, # assign 5 to x x = 5. Here, = is an assignment operator that assigns 5 to x. Here's a list of different assignment operators available in Python.

  13. Different Assignment operators in Python

    Simple assignment operator in Python. The Simple assignment operator in Python is denoted by = and is used to assign values from the right side of the operator to the value on the left side.. Input: a = b + c Add and equal operator. This operator adds the value on the right side to the value on the left side and stores the result in the operand on the left side.

  14. Python Assignment Operator

    Python comes with a couple of shorthand assignment operators. Some of the most common ones include the following: Operator. Meaning. +=. Add the value on the right to the variable on the left. -=. Subtract the value on the right from the variable on the left. *=.

  15. Python For Beginners

    00:00 - Start00:17 - What are operators?00:34 - What is an assignment operator01:21 - How to increment a variable03:13 - Other arithmetic operators

  16. Python Assignment Operators Explained Simply (Full Tutorial)

    Assignment operators in Python are used to assign values to variables. These operators make the code more concise and easier to read. In this video we shorth...

  17. Python Assignment Operators

    Assignment Operators are used for assigning values to the variables. We can also say that assignment operators are used to assign values that are available on the right-hand side to the left-hand side operand. For example, in the below table, we are assigning a value to variable 'a', which is the left-side operand. Operator.

  18. Assignment Operator in Python

    The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is: variable = value. Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example.

  19. Python Operators Explained in Detail with Examples

    Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.

  20. Python Operators

    Python Identity Operators. Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator. Description. Example. Try it. is. Returns True if both variables are the same object. x is y.

  21. Assignment Operators in Python

    Python Programming: Assignment Operators in PythonTopics discussed:1. Introduction to Assignment Operators.2. Assignment Operators in Python.Python Programmi...

  22. [Python] Assignment Operators with Examples Explained

    Beyond the basic assignment (=), Python also provides a suite of compound assignment operators that combine arithmetic operations with assignment, streamlining code and enhancing readability. The Basic Assignment Operator (=) The basic assignment operator in Python is =. It's used to assign a value to a variable.

  23. An in-depth guide to operators in Python

    Python Assignment Operators. We've already explained the use of the equal sign (=) ... Just like in mathematics, operators in Python have a specific order of precedence that determines the order in which operations are performed. Exponentiation (**) Complement, unary plus, and minus (e.g. ~x, +x, -x) ...

  24. Welcome to Python.org

    The core of extensible programming is defining functions. Python allows mandatory and optional arguments, keyword arguments, and even arbitrary argument lists. More about defining functions in Python 3. Python is a programming language that lets you work quickly and integrate systems more effectively. Learn More.