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
  • Python - OS Path Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Classes & Objects
  • 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 Advanced Concepts
  • Python - Abstract Base Classes
  • Python - Custom Exceptions
  • Python - Higher Order Functions
  • Python - Object Internals
  • Python - Memory Management
  • Python - Metaclasses
  • Python - Metaprogramming with Metaclasses
  • Python - Mocking and Stubbing
  • Python - Monkey Patching
  • Python - Signal Handling
  • Python - Type Hints
  • Python - Automation Tutorial
  • Python - Humanize Package
  • Python - Context Managers
  • Python - Coroutines
  • Python - Descriptors
  • Python - Diagnosing and Fixing Memory Leaks
  • Python - Immutable Data Structures
  • Python Useful Resources
  • Python - Questions & Answers
  • Python - Online Quiz
  • Python - Quick Guide
  • Python - Projects
  • Python - Useful Resources
  • Python - Discussion
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • 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.

01 Career Opportunities

02 beginner, 03 intermediate, 04 training programs, assignment operators in python, what is an assignment operator in python.

.

Types of Assignment Operators in Python

1. simple python assignment operator (=), example of simple python assignment operator, 2. augmented assignment operators in python, 1. augmented arithmetic assignment operators in python.

+=Addition Assignment Operator
-=Subtraction Assignment Operator
*=Multiplication Assignment Operator
/=Division Assignment Operator
%=Modulus Assignment Operator
//=Floor Division Assignment Operator
**=Exponentiation Assignment Operator

2. Augmented Bitwise Assignment Operators in Python

&=Bitwise AND Assignment Operator
|=Bitwise OR Assignment Operator
^=Bitwise XOR Assignment Operator
>>=Bitwise Right Shift Assignment Operator
<<=Bitwise Left Shift Assignment Operator

Augmented Arithmetic Assignment Operators in Python

1. augmented addition operator (+=), example of augmented addition operator in python, 2. augmented subtraction operator (-=), example of augmented subtraction operator in python, 3. augmented multiplication operator (*=), example of augmented multiplication operator in python, 4. augmented division operator (/=), example of augmented division operator in python, 5. augmented modulus operator (%=), example of augmented modulus operator in python, 6. augmented floor division operator (//=), example of augmented floor division operator in python, 7. augmented exponent operator (**=), example of augmented exponent operator in python, augmented bitwise assignment operators in python, 1. augmented bitwise and (&=), example of augmented bitwise and operator in python, 2. augmented bitwise or (|=), example of augmented bitwise or operator in python, 3. augmented bitwise xor (^=), example of augmented bitwise xor operator in python, 4. augmented bitwise right shift (>>=), example of augmented bitwise right shift operator in python, 5. augmented bitwise left shift (<<=), example of augmented bitwise left shift operator in python, walrus operator in python, syntax of an assignment expression, example of walrus operator in python.

Live Classes Schedule

Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast

About Author

Assignment Operators

Add and assign, subtract and assign, multiply and assign, divide and assign, floor divide and assign, exponent and assign, modulo and assign.

to

to and assigns the result to

from and assigns the result to

by and assigns the result to

with and assigns the result to ; the result is always a float

with and assigns the result to ; the result will be dependent on the type of values used

to the power of and assigns the result to

is divided by and assigns the result to

For demonstration purposes, let’s use a single variable, num . Initially, we set num to 6. We can apply all of these operators to num and update it accordingly.

Assigning the value of 6 to num results in num being 6.

Expression: num = 6

Adding 3 to num and assigning the result back to num would result in 9.

Expression: num += 3

Subtracting 3 from num and assigning the result back to num would result in 6.

Expression: num -= 3

Multiplying num by 3 and assigning the result back to num would result in 18.

Expression: num *= 3

Dividing num by 3 and assigning the result back to num would result in 6.0 (always a float).

Expression: num /= 3

Performing floor division on num by 3 and assigning the result back to num would result in 2.

Expression: num //= 3

Raising num to the power of 3 and assigning the result back to num would result in 216.

Expression: num **= 3

Calculating the remainder when num is divided by 3 and assigning the result back to num would result in 2.

Expression: num %= 3

We can effectively put this into Python code, and you can experiment with the code yourself! Click the “Run” button to see the output.

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.

Python Assignment Operators: A Beginner’s Guide with Examples

Python offers a variety of tools to manipulate and manage data. Among these are assignment operators, which enable programmers to assign values to variables in a concise and efficient manner. Whether you’re a newcomer to programming or just getting started with Python, understanding assignment operators is a fundamental step toward becoming a proficient coder. In this article, we’ll explore the basics of Python assignment operators with clear examples to help beginners grasp their usage effectively.

Table of Contents

1. What are Assignment Operators?

2. examples of assignment operators., 2.1 basic assignment (=)., 2.2 add and assign (+=)., 2.3 subtract and assign (-=)., 2.4 multiply and assign (*=)., 2.5 divide and assign (/=)., 2.6 modulus and assign (%=)., 3. conclusion., leave a comment cancel reply.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

theme logo

Logical Python

Effective Python Tutorials

Python Assignment Operators

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

OperatorDescriptionExampleEquivalent
= a = 2a = 2
+= a += 2a = a + 2
-= a -= 2a = a – 2
*= a *= 2a = a * 2
/= a /= 2a = a / 2
%= a %= 2a = a % 2
//= a //= 2a = a // 2
**= a **= 2a = a ** 2
&= a &= 2a = a & 2
|= a |= 2a = a | 2
^= a ^= 2a = a ^ 2
>>= a >>= 2a = a >> 2
<<= a <<= 3a = a << 2

Assignment Operators

Assignment operator.

Equal to sign ‘=’ is used as an assignment operator. It assigns values of the right-hand side expression to the variable or operand present on the left-hand side.

Assigns value 3 to variable ‘a’.

Addition and Assignment Operator

The addition and assignment operator adds left-side and right-side operands and then the sum is assigned to the left-hand side operand.

Below code is equivalent to:  a = a + 2.

Subtraction and Assignment Operator

The subtraction and assignment operator subtracts the right-side operand from the left-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a – 2.

Multiplication and Assignment Operator

The multiplication and assignment operator multiplies the right-side operand with the left-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a * 2.

Division and Assignment Operator

The division and assignment operator divides the left-side operand with the right-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a / 2.

Modulus and Assignment Operator

The modulus and assignment operator divides the left-side operand with the right-side operand, and then the remainder is assigned to the left-hand side operand.

Below code is equivalent to:  a = a % 3.

Floor Division and Assignment Operator

The floor division and assignment operator divides the left side operand with the right side operand. The result is rounded down to the closest integer value(i.e. floor value) and is assigned to the left-hand side operand.

Below code is equivalent to:  a = a // 3.

Exponential and Assignment Operator

The exponential and assignment operator raises the left-side operand to the power of the right-side operand, and the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a ** 3.

Bitwise AND and Assignment Operator

Bitwise AND and assignment operator performs bitwise AND operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a & 3.

Illustration:

Numeric ValueBinary Value
2010
3011

Bitwise OR and Assignment Operator

Bitwise OR and assignment operator performs bitwise OR operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a | 3.

Bitwise XOR and Assignment Operator

Bitwise XOR and assignment operator performs bitwise XOR operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a ^ 3.

Bitwise Right Shift and Assignment Operator

Bitwise right shift and assignment operator right shifts the left operand by the right operand positions and assigns the result to the left-hand side operand.

Below code is equivalent to:  a = a >> 1.

Numeric InputBinary ValueRight shift by 1Numeric Output
2001000011
4010000102

Bitwise Left Shift and Assignment Operator

Bitwise left shift and assignment operator left shifts the left operand by the right operand positions and assigns the result to the left-hand side operand.

Below code is equivalent to:  a = a << 1.

Numeric InputBitwise ValueLeft shift by 1Numeric Output
2001001004
4010010008

References:

  • Different Assignment operators in Python
  • Assignment Operator in Python
  • Assignment Expressions

assignment operators in python example

Assignment Operators in Python

Assignment Operators in Python

Table of Contents

Assignment Operators will work on values and variables. They are the special symbols that hold arithmetic, logical, and bitwise computations. The value which the operator operates is referred to as the Operand.

Read this article about Assignment Operators in Python

What are Assignment Operators?

The assignment operator will function to provide value to variables. The table below is about the different types of Assignment operator

+= will add right side operand with left side operand, assign to left operand a+=b
= It will assign the value of the right side of the expression to the left side operandx=y+z
-= can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala -= b  
*= can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala *= b     
/= will divide the left operand with right operand and then assign to the left operanda /= b
%= will divide the left operand with the right operand and then assign to the left operanda %= b  
<<=
It functions bitwise left on operands and will assign value to the left operand a <<= b 
>>=
This operator will perform right shift on operands and can assign value to the left operanda >>= b     

^=
This will function the bitwise xOR operands and can assign value to the left operand a ^= b    

|=
This will function Bitwise OR operands and will provide value to the left operand.a |= b    

&=
This operator will perform Bitwise AND on operand and can provide value to the left operanda&=b
**=
operator will evaluate the exponent value with the help of operands an assign value to the left operanda**=b

Here we have listed each of the Assignment operators

1. What is Assign Operator?

This assign operator will provide the value of the right side of the expression to the left operand.

2. What is Add and Assign

This Add and Assign operator will function to add the right side operand with the left side operator, and provide the result to the left operand.

3. What is Subtract and assign ?

This subtract and assign operator works to subtract the right operand from the left operand and give the result to the left operand.

4. What is Multiply and assign ?

This Multiply and assign will function to multiply the right operand with the left operand and will provide the result in the left operand.

5. What is Divide and assign Operator?

This functions to divide the left operand and provides results at the left operand.

6. What is Modulus and Assign Operator?

This operator functions using the modulus with the left and the right operand and provides results at the left operand.

7. What is Divide ( floor)and Assign Operator?

This operator will divide the left operand with the right operand, and provide the result at the left operand.

8. What is Exponent and Assign Operator?

This operator will function to evaluate the exponent and value with the operands and, provide output in the left operand.

9.What is Bitwise and Assign Operator?

This operator will function Bitwise AND on both the operand and provide the result on the left operand.

10. What is Bitwise OR and Assign Operator?

This operand will function Bitwise OR on the operand, and can provide result at the left operand.

11. What is Bitwise XOR and Assign Operator?

This operator will function for Bitwise XOR on the operands, and provide result at the left operand.

12. What is Bitwise Right Shift and Assign Operator?

This operator will function by providing the Bitwise shift on the operands and giving the result at the left operand.

13. What is Bitwise Left shift and Assign Operator?

This operator will function Bitwise left shift by providing the Bitwise left shift on the operands and giving the result on the left operand.

To conclude, different types of assignment operators are discussed in this. Beginners can improve their knowledge and understand how to apply the assignment operators through reading this.

Assignment Operators in Python- FAQs

Q1. what is an assignment statement in python.

Ans. It will calculate the expression list and can provide a single resulting object to each target list from left to right

Q2. What is the compound operator in Python?

Ans. The compound operator will do the operation of a binary operator and will save the result of the operation at the left operand.

Q3. What are the two types of assignment statements

Ans. Simple Assignment Statements and Reference Assignment Statements are the two types of assignment statements.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Python Logical Operators

Python Bitwise Operator

Leave a Comment Cancel reply

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

Reach Out to Us for Any Query

SkillVertex is an edtech organization that aims to provide upskilling and training to students as well as working professionals by delivering a diverse range of programs in accordance with their needs and future aspirations.

© 2024 Skill Vertex

Python Assignment Operators

Python Assignment OperatorsExampleExplanation
=x= 25Value 25 is assigned to x
+=x += 25This is same as x = x + 25
-=x -= 25Same as x = x – 25
*=x *= 25This is same as x = x * 25
/=x /= 25Same as x = x / 25
%=x %= 25This is identical to x = x % 25
//=x //= 25Same as x = x // 25
**=x **= 25This is same as x = x ** 25
&=x &= 25This is same as x = x & 25
|=x |= 25This is same as x = x | 25
^=x ^= 25Same as x = x ^ 25
<<=x <<= 25This is same as x = x << 25
>>=x >>= 25Same as x = x >> 25

Python Assignment Operators Example

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

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:

Operation Operator Function Example in Python Shell
Sum of two operands + operator.add(a,b)
Left operand minus right operand - operator.sub(a,b)
* operator.mul(a,b)
Left operand raised to the power of right ** operator.pow(a,b)
/ operator.truediv(a,b)
equivilant to // operator.floordiv(a,b)
Reminder of % operator.mod(a, b)

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

Operator Function Example in Python Shell
=
+= operator.iadd(a,b)
-= operator.isub(a,b)
*= operator.imul(a,b)
/= operator.itruediv(a,b)
//= operator.ifloordiv(a,b)
%= operator.imod(a, b)
&= operator.iand(a, b)
|= operator.ior(a, b)
^= operator.ixor(a, b)
>>= operator.irshift(a, b)
<<= operator.ilshift(a, b)

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

Operator Function Description Example in Python Shell
> operator.gt(a,b) True if the left operand is higher than the right one
< operator.lt(a,b) True if the left operand is lower than right one
== operator.eq(a,b) True if the operands are equal
!= operator.ne(a,b) True if the operands are not equal
>= operator.ge(a,b) True if the left operand is higher than or equal to the right one
<= operator.le(a,b) True if the left operand is lower than or equal to the right one

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.

Operator Description Example
and True if both are true
or True if at least one is true
not Returns True if an expression evalutes to false and vice-versa

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

Operator Function Description Example in Python Shell
is operator.is_(a,b) True if both are true
is not operator.is_not(a,b) True if at least one is true

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 .

Operator Function Description Example in Python Shell
in operator.contains(a,b) Returns True if the sequence contains the specified item else returns False.
not in not operator.contains(a,b) Returns True if the sequence does not contains the specified item, else returns False.

Bitwise operators perform operations on binary operands.

Operator Function Description Example in Python Shell
& operator.and_(a,b) Sets each bit to 1 if both bits are 1.
| operator.or_(a,b) Sets each bit to 1 if one of two bits is 1.
^ operator.xor(a,b) Sets each bit to 1 if only one of two bits is 1.
~ operator.invert(a) Inverts all the bits.
<< operator.lshift(a,b) Shift left by pushing zeros in from the right and let the leftmost bits fall off.
>> operator.rshift(a,b) Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.
  • 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

assignment operators in python example

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

The Walrus Operator: Python's Assignment Expressions

The Walrus Operator: Python's Assignment Expressions

Table of Contents

Hello, Walrus!

Implementation, lists and dictionaries, list comprehensions, while loops, witnesses and counterexamples, walrus operator syntax, walrus operator pitfalls.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Assignment Expressions and Using the Walrus Operator

Each new version of Python adds new features to the language. Back when Python 3.8 was released, the biggest change was the addition of assignment expressions . Specifically, the := operator gave you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator .

This tutorial is an in-depth introduction to the walrus operator. You’ll learn some of the motivations for the syntax update and explore examples where assignment expressions can be useful.

In this tutorial, you’ll learn how to:

  • Identify the walrus operator and understand its meaning
  • Understand use cases for the walrus operator
  • Avoid repetitive code by using the walrus operator
  • Convert between code using the walrus operator and code using other assignment methods
  • Use appropriate style in your assignment expressions

Note that all walrus operator examples in this tutorial require Python 3.8 or later to work.

Get Your Code: Click here to download the free sample code that shows you how to use Python’s walrus operator.

Take the Quiz: Test your knowledge with our interactive “The Walrus Operator: Python's Assignment Expressions” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

In this quiz, you'll test your understanding of the Python Walrus Operator. This operator was introduced in Python 3.8, and understanding it can help you write more concise and efficient code.

Walrus Operator Fundamentals

First, look at some different terms that programmers use to refer to this new syntax. You’ve already seen a few in this tutorial.

The := operator is officially known as the assignment expression operator . During early discussions, it was dubbed the walrus operator because the := syntax resembles the eyes and tusks of a walrus lying on its side. You may also see the := operator referred to as the colon equals operator . Yet another term used for assignment expressions is named expressions .

To get a first impression of what assignment expressions are all about, start your REPL and play around with the following code:

Line 1 shows a traditional assignment statement where the value False is assigned to walrus . Next, on line 5, you use an assignment expression to assign the value True to walrus . After both lines 1 and 5, you can refer to the assigned values by using the variable name walrus .

You might be wondering why you’re using parentheses on line 5, and you’ll learn why the parentheses are needed later on in this tutorial .

Note: A statement in Python is a unit of code. An expression is a special statement that can be evaluated to some value.

For example, 1 + 2 is an expression that evaluates to the value 3 , while number = 1 + 2 is an assignment statement that doesn’t evaluate to a value. Although running the statement number = 1 + 2 doesn’t evaluate to 3 , it does assign the value 3 to number .

In Python, you often see simple statements like return statements and import statements , as well as compound statements like if statements and function definitions . These are all statements, not expressions.

There’s a subtle—but important—difference between the two types of assignments with the walrus variable. An assignment expression returns the value, while a traditional assignment doesn’t. You can see this in action when the REPL doesn’t print any value after walrus = False on line 1 but prints out True after the assignment expression on line 5.

You can see another important aspect about walrus operators in this example. Though it might look new, the := operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient and can sometimes communicate the intent of your code more clearly.

Now you have a basic idea of what the := operator is and what it can do. It’s an operator used in assignment expressions, which can return the value being assigned, unlike traditional assignment statements. To get deeper and really learn about the walrus operator, continue reading to see where you should and shouldn’t use it.

Like most new features in Python, assignment expressions were introduced through a Python Enhancement Proposal (PEP). PEP 572 describes the motivation for introducing the walrus operator, the details of the syntax, and examples where the := operator can be used to improve your code.

This PEP was originally written by Chris Angelico in February 2018. Following some heated discussion, PEP 572 was accepted by Guido van Rossum in July 2018.

Since then, Guido announced that he was stepping down from his role as benevolent dictator for life (BDFL) . Since early 2019, the Python language has been governed by an elected steering council instead.

The walrus operator was implemented by Emily Morehouse , and made available in the first alpha release of Python 3.8.

In many languages, including C and its derivatives, assignment statements are also expressions. This can be both very powerful and a source of confusing bugs. For example, the following code is valid C but doesn’t execute as intended:

Here, if (x = y) will evaluate to true, and the code snippet will print out x and y are equal (x = 8, y = 8) . Is this the result you were expecting? You were trying to compare x and y . How did the value of x change from 3 to 8 ?

The problem is that you’re using the assignment operator ( = ) instead of the equality comparison operator ( == ). In C, x = y is an expression that evaluates to the value of y . In this example, x = y is evaluated as 8 , which is considered truthy in the context of the if statement.

Take a look at a corresponding example in Python. This code causes a SyntaxError :

Unlike the C example, this Python code gives you an explicit error instead of a bug.

The distinction between assignment statements and assignment expressions in Python is useful in order to avoid these kinds of hard-to-find bugs. PEP 572 argues that Python is better suited to having different syntax for assignment statements and expressions instead of turning the existing assignment statements into expressions.

One design principle underpinning the walrus operator is that there are no identical code contexts where both an assignment statement using the = operator and an assignment expression using the := operator would be valid. For example, you can’t do a plain assignment with the walrus operator:

In many cases, you can add parentheses ( () ) around the assignment expression to make it valid Python:

Writing a traditional assignment statement with = isn’t allowed inside such parentheses. This helps you catch potential bugs.

Later on in this tutorial , you’ll learn more about situations where the walrus operator isn’t allowed, but first you’ll learn about the situations where you might want to use it.

Walrus Operator Use Cases

In this section, you’ll see several examples where the walrus operator can simplify your code. A general theme in all these examples is that you’ll avoid different kinds of repetition:

  • Repeated function calls can make your code slower than necessary.
  • Repeated statements can make your code hard to maintain.
  • Repeated calls that exhaust iterators can make your code overly complex.

You’ll see how the walrus operator can help in each of these situations.

Arguably one of the best use cases for the walrus operator is when debugging complex expressions. Say that you want to find the distance between two locations along the earth’s surface. One way to do this is to use the haversine formula :

The haversine formula

ϕ represents the latitude, and λ represents the longitude of each location. To demonstrate this formula, you can calculate the distance between Oslo (59.9°N 10.8°E) and Vancouver (49.3°N 123.1°W) as follows:

As you can see, the distance from Oslo to Vancouver is just under 7,200 kilometers.

Note: Python source code is typically written using UTF-8 Unicode . This allows you to use Greek letters like ϕ and λ in your code, which may be useful when translating mathematical formulas. Wikipedia shows some alternatives for using Unicode on your system.

While UTF-8 is supported (in string literals, for instance), Python’s variable names use a more limited character set . For example, you can’t use emojis while naming your variables. That’s a good restriction !

Now, say that you need to double-check your implementation and want to see how much the haversine terms contribute to the final result. You could copy and paste the term from your main code to evaluate it separately. However, you could also use the := operator to give a name to the subexpression that you’re interested in:

The advantage of using the walrus operator here is that you calculate the value of the full expression and keep track of the value of ϕ_hav at the same time. This allows you to confirm that you didn’t introduce any errors while debugging.

Lists are powerful data structures in Python that often represent a series of related attributes. Similarly, dictionaries are used all over Python and are great for structuring information.

Sometimes when setting up these data structures, you end up performing the same operation several times. As a first example, calculate some basic descriptive statistics of a list of numbers and store them in a dictionary:

Note that both the sum and the length of the numbers list are calculated twice. The consequences are not too bad in this simple example, but if the list were larger or the calculations were more complicated, you might want to optimize the code. To do this, you can first move the function calls out of the dictionary definition:

The variables num_length and num_sum are only used to optimize the calculations inside the dictionary. By using the walrus operator, you can make this role clearer:

You’ve now defined num_length and num_sum inside the definition of description . This is a clear hint to anybody reading this code that these variables are just used to optimize these calculations and aren’t used again later.

Note: The scope of the num_length and num_sum variables is the same in the example with the walrus operator and in the example without. This means that in both examples, the variables are available after the definition of description .

Even though both examples are very similar functionally, a benefit of using the assignment expressions is that the := operator communicates the intent of these variables as throwaway optimizations.

In the next example, you’ll work with a bare-bones implementation of the wc utility for counting lines, words, and characters in a text file:

This script can read one or several text files and report how many lines, words, and characters each of them contains. Here’s a breakdown of what’s happening in the code:

  • Line 4 loops over each filename provided by the user. The sys.argv list contains each argument given on the command line, starting with the name of your script. For more information about sys.argv , you can check out Python Command Line Arguments .
  • Line 5 converts each filename string to a pathlib.Path object . Storing a filename in a Path object allows you to conveniently read the text file in the next lines.
  • Lines 6 to 10 construct a tuple of counts to represent the number of lines, words, and characters in one text file.
  • Line 7 reads a text file and calculates the number of lines by counting newlines.
  • Line 8 reads a text file and calculates the number of words by splitting on whitespace.
  • Line 9 reads a text file and calculates the number of characters by finding the length of the string.
  • Line 11 prints all three counts together with the filename to the console. The *counts syntax unpacks the counts tuple. In this case, the print() statement is equivalent to print(counts[0], counts[1], counts[2], path) .

To see wc.py in action, you can use the script on itself as follows:

In other words, the wc.py file consists of 11 lines, 32 words, and 307 characters.

If you look closely at this implementation, then you’ll notice that it’s far from optimal. In particular, it repeats the call to path.read_text() three times. That means that the program reads each text file three times. You can use the walrus operator to avoid the repetition:

You assign the contents of the file to text , which you reuse in the next two calculations. Note the placement of parentheses that help scope that text will refer to the text in the file and not the number of lines.

The program still functions the same, although the word and character counts have changed:

As in the earlier examples, an alternative approach is to define text before the definition of counts :

While this is one line longer than the previous implementation, it probably provides the best balance between readability and efficiency. The := assignment expression operator isn’t always the most readable solution even when it makes your code more concise.

List comprehensions are great for constructing and filtering lists. They clearly state the intent of the code and will usually run quite fast.

There’s one list comprehension use case where the walrus operator can be particularly useful. Say that you want to apply some computationally expensive function, slow() , to the elements in your list and filter on the resulting values. You could do something like the following:

Here, you filter the numbers list and leave the positive results from applying slow() . The problem with this code is that this expensive function is called twice.

A very common solution for this type of situation is rewriting your code to use an explicit for loop:

This will only call slow() once. Unfortunately, the code is now more verbose, and the intent of the code is harder to understand. The list comprehension had clearly signaled that you were creating a new list, while this is more hidden in the explicit for loop since several lines of code separate the list creation and the use of .append() . Additionally, a list comprehension runs faster than the repeated calls to .append() .

You can code some other solutions by using a filter() expression or a kind of double list comprehension:

The good news is that there’s only one call to slow() for each number. The bad news is that the code’s readability has suffered in both expressions.

Figuring out what’s actually happening in the double list comprehension takes a fair amount of head-scratching. Essentially, the second for statement is used only to give the name value to the return value of slow(num) . Fortunately, that sounds like something that you can accomplish with an assignment expression!

You can rewrite the list comprehension using the walrus operator as follows:

Note that the parentheses around value := slow(num) are required. This version is effective and readable, and it communicates the intent of the code well.

Note: You need to add the assignment expression on the if clause of the list comprehension. If you try to define value with the other call to slow() , then it won’t work:

This will raise a NameError because the if clause is evaluated before the expression at the beginning of the comprehension.

Next, look at a slightly more involved and practical example. Say that you want to use the Real Python feed to find the titles of the last episodes of the Real Python Podcast .

You can use the Real Python Feed Reader to download information about the latest Real Python publications. In order to find the podcast episode titles, you’ll use the third-party Parse package. Start by creating a virtual environment and installing both packages:

You can now read the latest titles published by Real Python:

Podcast titles start with "The Real Python Podcast" , so here you can create a pattern that Parse can use to identify them:

Compiling the pattern beforehand speeds up later comparisons, especially when you want to match the same pattern over and over. You can check if a string matches your pattern using either pattern.parse() or pattern.search() :

Note that Parse is able to pick out the podcast episode number and the episode name. The episode number is converted to an integer data type because you used the :d format specifier .

Time to get back to the task at hand. In order to list all the recent podcast titles, you need to check whether each string matches your pattern and then parse out the episode title. A first attempt may look something like this:

Though it works, you might notice the same problem you saw earlier. You’re parsing each title twice because you filter out titles that match your pattern and then use that same pattern to pick out the episode title.

Like you did earlier, you can avoid the double work by rewriting the list comprehension using either an explicit for loop or a double list comprehension. Using the walrus operator, however, is even more straightforward:

Assignment expressions work well to simplify these kinds of list comprehensions. They keep your code readable and save you from doing a potentially expensive operation twice.

Note: The Real Python Podcast has its own separate RSS feed , which you should use if you want to play around with information about the podcast only. You can get all the episode titles with the following code:

See The Real Python Podcast for options to listen to it using your podcast player.

In this section, you’ve focused on examples where you can rewrite list comprehensions using the walrus operator. The same principles also apply if you see that you need to repeat an operation in a dictionary comprehension , a set comprehension , or a generator expression .

The following example uses a generator expression to calculate the average length of episode titles that are over 50 characters long:

The generator expression uses an assignment expression to avoid calculating the length of each episode title twice.

Python has two different loop constructs: for loops and while loops . You typically use a for loop when you need to iterate over a known sequence of elements. A while loop, on the other hand, is for when you don’t know beforehand how many times you’ll need to repeat the loop.

In while loops, you need to define and check the ending condition at the top of the loop. This sometimes leads to some awkward code when you need to do some setup before performing the check. Here’s a snippet from a multiple-choice quiz program that asks the user to answer a question with one of several valid answers:

This works but has an unfortunate repetition of two identical input() lines. It’s necessary to get at least one answer from the user before checking whether it’s valid or not. You then have a second call to input() inside the while loop to ask for a second answer in case the original user_answer wasn’t valid.

If you want to make your code more maintainable, it’s quite common to rewrite this kind of logic with a while True loop. Instead of making the check part of the main while statement, the check is performed later in the loop together with an explicit break :

This has the advantage of avoiding the repetition. However, the actual check is now harder to spot.

Assignment expressions can simplify these kinds of loops. In this example, you can now put the check back together with while where it makes more sense:

The while statement is a bit denser, but the code now communicates the intent more clearly without repeated lines or seemingly infinite loops.

You can expand the box below to see the full code of the multiple-choice quiz program and try a couple of questions about the walrus operator yourself.

Full source code of multiple-choice quiz program Show/Hide

This script runs a multiple-choice quiz. You’ll be asked each of the questions in order, but the order of answers will be shuffled each time:

Note that the first answer is assumed to be the correct one, while the others serve as distractors. You can add more questions to the quiz yourself. Feel free to share your questions with the community in the comments section below the tutorial!

See Build a Quiz Application With Python if you want to dive deeper into using Python to quiz yourself or your friends. You can also quiz yourself on your knowledge of the walrus operator:

You can often simplify while loops by using assignment expressions. The original PEP shows an example from the standard library that makes the same point.

In the examples you’ve seen so far, the := assignment expression operator does essentially the same job as the = assignment operator in your old code. You’ve seen how to simplify code, and now you’ll learn about a different type of use case that this operator makes possible.

In this section, you’ll learn how you can find witnesses when calling any() by using a clever trick that isn’t immediately possible without using the walrus operator. A witness, in this context, is an element that satisfies the check and causes any() to return True .

By applying similar logic, you’ll also learn how you can find counterexamples when working with all() . A counterexample, in this context, is an element that doesn’t satisfy the check and causes all() to return False .

In order to have some data to work with, define the following list of city names:

You can use any() and all() to answer questions about your data:

In each of these cases, any() and all() give you plain True or False answers. What if you’re also interested in seeing an example or a counterexample of the city names? It could be nice to see what’s causing your True or False result:

Does any city name start with "B" ?

Yes, because "Berlin" starts with "B" .

Do all city names start with "B" ?

No, because "Oslo" doesn’t start with "B" .

In other words, you want a witness or a counterexample to justify the answer.

Capturing a witness to an any() expression has not been intuitive in earlier versions of Python. If you were calling any() on a list and then realized you also wanted a witness, you’d typically need to rewrite your code:

Here, you first capture all city names that start with "B" . Then, if there’s at least one such city name, you print out the first city name starting with "B" . Note that here you’re actually not using any() even though you’re doing a similar operation with the list comprehension.

By using the := operator, you can find witnesses directly in your any() expressions:

You can capture a witness inside the any() expression. The reason this works is a bit subtle and relies on any() and all() using short-circuit evaluation : they only check as many items as necessary to determine the result.

Note: If you want to check whether all city names start with the letter "B" , then you can look for a counterexample by replacing any() with all() and updating the print() functions to report the first item that doesn’t pass the check.

You can more clearly see what’s happening by wrapping .startswith("B") in a function that also prints out which item is being checked:

Note that any() doesn’t actually check all the items in cities . It only checks items until it finds one that satisfies the condition. Combining the := operator and any() works by iteratively assigning each item that is being checked to witness . However, only the last such item survives and shows which item was last checked by any() .

Even when any() returns False , a witness is found:

However, in this case, witness doesn’t give any insight. 'Belgrade' doesn’t contain ten or more characters. The witness only shows which item happened to be evaluated last.

One of the main reasons assignments weren’t expressions in Python from the beginning is that the visual similarity of the assignment operator ( = ) and the equality comparison operator ( == ) could potentially lead to bugs.

When introducing assignment expressions, the developers put a lot of thought into how to avoid similar bugs with the walrus operator. As mentioned earlier , one important feature is that the := operator is never allowed as a direct replacement for the = operator, and vice versa.

As you saw at the beginning of this tutorial, you can’t use a plain assignment expression to assign a value:

It’s syntactically legal to use an assignment expression to only assign a value, but you need to add parentheses:

Even though it’s possible, this is a prime example of where you should stay away from the walrus operator and use a traditional assignment statement instead.

PEP 572 shows several other examples where the := operator is either illegal or discouraged. The following examples all cause a SyntaxError :

In all these cases, you’re better served using = instead. The next examples are similar and are all legal code. However, the walrus operator doesn’t improve your code in any of these cases:

None of these examples make your code more readable. You should instead do the extra assignment separately by using a traditional assignment statement. See PEP 572 for more details about the reasoning.

There’s one use case where the := character sequence is already valid Python. In f-strings , you use a colon ( : ) to separate values from their format specification . For example:

The := in this case does look like a walrus operator, but the effect is quite different. To interpret x:=8 inside the f-string, the expression is broken into three parts: x , : , and =8 .

Here, x is the value, : acts as a separator, and =8 is a format specification. According to Python’s Format Specification Mini-Language , in this context = specifies an alignment option. In this case, the value is padded with spaces in a field of width 8 .

To use assignment expressions inside f-strings, you need to add parentheses:

This updates the value of x as expected. However, you’re probably better off using traditional assignments outside of your f-strings instead.

Now, look at some other situations where assignment expressions are illegal:

Attribute and item assignment: You can only assign to simple names, not dotted or indexed names:

This fails with a descriptive error message. There’s no straightforward workaround.

Iterable unpacking: You can’t unpack when using the walrus operator:

If you add parentheses around the whole expression, then Python will interpret it as a 3-tuple with the three elements lat , 59.9 , and 10.8 .

Augmented assignment: You can’t use the walrus operator combined with augmented assignment operators like += . This raises a SyntaxError :

The easiest workaround would be to do the augmentation explicitly. You could, for example, do (count := count + 1) . PEP 577 originally described how to add augmented assignment expressions to Python, but the proposal was withdrawn.

When you’re using the walrus operator, it’ll behave similarly to traditional assignment statements in many respects:

The scope of the assignment target is the same as for assignments. It’ll follow the LEGB rule . Typically, the assignment will happen in the local scope, but if the target name is already declared global or nonlocal , that declaration is honored.

The precedence of the walrus operator can cause some confusion. It binds less tightly than all other operators except the comma, so you might need parentheses to delimit the expression that you’re assigning. As an example, note what happens when you don’t use parentheses:

square is bound to the whole expression number ** 2 > 5 . In other words, square gets the value True and not the value of number ** 2 , which was the intention. In this case, you can delimit the expression with parentheses:

The parentheses make the if statement both clearer and actually correct.

There’s one final gotcha. When assigning a tuple using the walrus operator, you always need to use parentheses around the tuple. Compare the following assignments:

Note that in the second example, walrus takes the value 3.8 and not the whole tuple 3.8, True . That’s because the := operator binds more tightly than the comma. This may seem a bit annoying. However, if the := operator bound less tightly than the comma, then it wouldn’t be possible to use the walrus operator in function calls with more than one argument.

The style recommendations for the walrus operator are mostly the same as for the = operator used for assignment. First, always add spaces around the := operator in your code. Second, use parentheses around the expression as necessary, but avoid adding extra parentheses that you don’t need.

The general design of assignment expressions is to make them easy to use when they’re helpful but to avoid overusing them when they might clutter up your code.

The walrus operator is a newer syntax that’s only available in Python 3.8 and later. This means that any code you write that uses the := syntax will only work on these versions of Python.

If you need to support legacy versions of Python, then you can’t ship code that uses assignment expressions. As you’ve learned in this tutorial, you can always write code without the walrus operator and stay compatible with older versions.

Experience with the walrus operator indicates that := will not revolutionize Python. Instead, using assignment expressions where they’re useful can help you make several small improvements to your code that could benefit your work overall.

You’ll run into several situations where it’s possible for you to use the walrus operator, but it won’t necessarily improve the readability or efficiency of your code. In those cases, you’re better off writing your code in a more traditional manner.

You now know how the walrus operator works and how you can use it in your own code. By using the := syntax, you can avoid different kinds of repetition in your code and make your code both more efficient and easier to read and maintain. At the same time, you shouldn’t use assignment expressions everywhere. They’ll only help you in specific use cases.

In this tutorial, you learned how to:

To learn more about the details of assignment expressions, see PEP 572 . You can also check out the PyCon 2019 talk PEP 572: The Walrus Operator , where Dustin Ingram gives an overview of both the walrus operator and the discussion around the new PEP.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Geir Arne Hjelle

Geir Arne Hjelle

Geir Arne is an avid Pythonista and a member of the Real Python tutorial team.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices

Recommended Video Course: Python Assignment Expressions and Using the Walrus Operator

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

The Walrus Operator: Python's Assignment Expressions (Sample Code)

🔒 No spam. We take your privacy seriously.

assignment operators in python example

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

assignment operators in python example

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.

Algor Cards

Cosa ne pensi di noi?

Il tuo nome

La tua email

assignment operators in python example

Assignment Operators in Python

Mappa concettuale.

assignment operators in python example

Python's assignment operators, including the basic `=` and compound operators like `+=`, `-=`, `*=`, and `/=`, are crucial for efficient variable assignment and data manipulation. These operators allow for concise code by combining arithmetic operations with assignment, and their understanding is key to writing clear and reliable programs. Overloading these operators in custom classes can further enhance code readability and expressiveness.

Mostra di più

Basic and Compound Assignment Operators

Basic assignment operator (=).

The basic assignment operator (=) assigns a value to a variable

Compound Assignment Operators (+=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=)

Arithmetic Compound Assignment Operators (+=, -=, *=, /=, %=)

Compound assignment operators combine arithmetic operations with assignment, allowing for more compact and readable code

Bitwise Compound Assignment Operators (&=, |=, ^=, >>=, <<=)

Bitwise compound assignment operators perform an operation on the variable's value and the right-hand operand before reassigning the result to the variable

Exponentiation Compound Assignment Operator (**=)

The exponentiation compound assignment operator (**=) performs exponentiation on the variable's value and the right-hand operand before reassigning the result to the variable

Overloading Assignment Operators in User-Defined Classes

Overloading assignment operators in user-defined classes allows for custom behaviors and higher levels of abstraction in object interaction

Operator Precedence

Understanding operator precedence.

Operator precedence determines the sequence in which operations are executed within an expression

Impact of Operator Precedence on Expressions

Operator precedence can significantly impact the result of complex expressions and should be carefully considered when writing code

Importance of Parentheses in Expressions

Using parentheses can clarify the intended order of operations and prevent errors in complex expressions

Vuoi creare mappe dal tuo materiale?

Inserisci un testo, carica una foto o un audio su Algor. In pochi secondi Algorino lo trasformerà per te in mappa concettuale, riassunto e tanto altro!

Impara con le flashcards di Algor Education

Clicca sulla singola scheda per saperne di più sull'argomento.

assignment operators in python example

In Python, the single equal sign (`______`) is used to assign the value to the variable's left.

assignment operators in python example

Basic assignment operator in Python

`=` is used to assign a value to a variable.

assignment operators in python example

Purpose of compound assignment operators

Simplify code by combining an operation with assignment, enhancing succinctness and performance.

assignment operators in python example

Examples of bitwise compound assignment operators

`&=`, `|=`, `^=`, `>>=`, `<<=` perform bitwise operations and reassign the result to the variable.

assignment operators in python example

To perform division and assign the result to the same variable in Python, the ______ operator is used.

Python 'magic methods' for operator overloading

Special methods like `__add__()` enable custom behavior for operators in classes.

Purpose of `__add__()` method in Python

Defines class response to `+=` operator, allowing intuitive operations like built-in types.

Abstraction benefit of operator overloading

Hides complex code, offers simple object interaction interface.

To ensure the correct order of operations, programmers may use ______ or simplify complex expressions.

parentheses

Basic Python assignment operator

The `=` operator assigns a value to a variable.

Python compound assignment operators

Operators like `+=`, `-=`, combine assignment with arithmetic operation, modifying variable in place.

Operator overloading in custom classes

Allows custom definition of assignment operators in classes to tailor object behavior.

Ecco un elenco delle domande più frequenti su questo argomento

What is the purpose of python's assignment operators, and can you give an example of a basic and a compound operator, what types of operations can python's compound assignment operators perform, how do python's assignment operators simplify code when performing mathematical operations, how does overloading assignment operators in python enhance user-defined classes, why is it important to understand operator precedence in python programming, what are the overall benefits of using python's assignment operators in programming, contenuti simili, esplora altre mappe su argomenti simili.

Close-up of a silicon microprocessor showing a complex lattice of metallic circuits on a bluish-gray background, with no text or symbols.

Understanding Processor Cores

Close-up of a computer motherboard with CPU, integrated circuits, capacitors and memory slots on green circuit board.

Bitwise Shift Operations in Computer Science

Close-up of a motherboard with CPU under heatsink, black fan, memory modules and various electronic components.

Computer Memory

Modern data center with rows of black servers illuminated by colored LEDs, symmetrical corridors and soft blue light reflecting on the glossy white floor.

The Significance of Terabytes in Digital Storage

Secondary storage devices on wooden surface, including silver external hard drive, colorful USB sticks and black SSD, with blurry books background.

Secondary Storage in Computer Systems

Close-up of a silicon microchip with intricate circuitry reflecting metallic colors, highlighting the complex network of electrical pathways.

The Importance of Bits in the Digital World

Hands carefully placing colored tiles on a dull gray surface, creating an incomplete mosaic in an uncluttered environment.

Karnaugh Maps: A Tool for Simplifying Boolean Algebra Expressions

assignment operators in python example

Non trovi quello che cercavi?

Cerca un argomento inserendo una frase o una parola chiave

Exploring Python's Assignment Operators

Hands of a person typing on a modern keyboard without markings with blurred background of a screen with Python code in an IDE.

Comprehensive Overview of Python Assignment Operators

Demonstrating python assignment operators through examples, customizing behavior with overloaded assignment operators in python, the significance of operator precedence in python expressions, concluding insights on python assignment operators.

Modifica disponibile

  • Read Tutorial
  • Watch Guide Video

If that is about as clear as mud don't worry we're going to walk through a number of examples. And one very nice thing about the syntax for assignment operators is that it is nearly identical to a standard type of operator. So if you memorize the list of all the python operators then you're going to be able to use each one of these assignment operators quite easily.

The very first thing I'm going to do is let's first make sure that we can print out the total. So right here we have a total and it's an integer that equals 100. Now if we wanted to add say 10 to 100 how would we go about doing that? We could reassign the value total and we could say total and then just add 10. So let's see if this works right here. I'm going to run it and you can see we have a hundred and ten. So that works.

large

However, whenever you find yourself performing this type of calculation what you can do is use an assignment operator. And so the syntax for that is going to get rid of everything here in the middle and say plus equals and then whatever value. In this case I want to add onto it.

So you can see we have our operator and then right afterward you have an equal sign. And this is going to do is exactly like what we had before. So if I run this again you can see total is a hundred and ten

large

I'm going to just so you have a reference in the show notes I'm going to say that total equals total plus 10. This is exactly the same as what we're doing right here we're simply using assignment in order to do it.

I'm going to quickly go through each one of the other elements that you can use assignment for. And if you go back and you reference the show notes or your own notes for whenever you kept track of all of the different operators you're going to notice a trend. And that is because they're all exactly the same. So here if I want to subtract 10 from the total I can simply use the subtraction operator here run it again. And now you can see we have 90. Now don't be confused because we only temporarily change the value to 1 10. So when I commented this out and I ran it from scratch it took the total and it subtracted 10 from that total and that's what got printed out.

large

I'm going to copy this and the next one down the line is going to be multiplication. So in this case I'm going to say multiply with the asterisk the total and I'm just going to say times two just so we can see exactly what the value is going to be. And now we can see that's 200 which makes sense.

large

So we've taken total we have multiplied it by two and we have piped the entire thing into the total variable. So far so good. As you may have guessed next when we're going to do is division. So now I'm going to say total and then we're going to perform this division assignment and we're going to say divide this by 10 run it and you can see it gives us the value and it converts it to a float of ten point zero.

large

Now if this is starting to get a little bit much. Let's take a quick pause and see exactly what this is doing. Remember that all we're doing here is it's a shortcut. You could still perform it the same way we have in number 3 I could say total is equal to the total divided by 10. And if I run this you'll see we get ten point zero. And let's see what this warning is it says redefinition of total type from int to float. So we don't have to worry about this and this for if you're building Python programs you're very rarely ever going to see the syntax and it's because we have this assignment operator right here. So that is for division. And we also have the ability to use floor division as well. So if I run this you're going to see it's 10. But one thing you may notice is it's 10 it's not ten point zero. So remember that our floor division returns an integer it doesn't return a floating-point number. So if that is what you want then you can perform that task just like we did there.

Next one on the list is our exponents. I'm going to say the total and we're going to say we're going to assign that to the total squared. So going to run this and we get ten thousand. Just like you'd expect. And we have one more which is the modulus operator. So here remember it is the percent equals 2. And this is going to return zero because 100 is even if we changed 100 to be 101. This is going to return one because remember the typical purpose of the modulus operator is to let you know if you're working with an event or an odd value.

large

Now with all this being said, I wanted to show you every different option that you could use the assignment operator on. But I want to say that the most common way that you're going to use this or the most common one is going to be this one right here where we're adding or subtracting. So those are going to be the two most common. And what usually you're going to use that for is when you're incrementing or decrementing values so a very common way to do this would actually be like we have our total right here. So we have a total of 100 and you could imagine it being a shopping cart and it's 100 dollars and you could say product 2 and set this equal to 120. And then if I say product 3 and set this equal to 10. And so what I could do here is I could say total plus equals product to and then we could take the value and say product 3 and now if I run this you can see the value is 230.

large

So that's a very common way whenever you want to generate a sum you can use this type of syntax which is much faster and it's also going to be a more pythonic way it's going to be the way you're going to see in standard Python programs whenever you're wanting to generate a sum and then reset and reassign the value.

So in review, that is how you can use assignment operators in Python.

devCamp does not support ancient browsers. Install a modern version for best experience.

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 and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • 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.

Operator Operation Example
Addition
Subtraction
Multiplication
Division
Floor Division
Modulo
Power

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.

Operator Name Example
Assignment Operator
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Remainder Assignment
Exponent Assignment

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.

Operator Meaning Example
Is Equal To gives us
Not Equal To gives us
Greater Than gives us
Less Than gives us
Greater Than or Equal To give us
Less Than or Equal To gives us

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 .

Operator Example Meaning
a b :
only if both the operands are
a b :
if at least one of the operands is
a :
if the operand is and vice-versa.

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)

Operator Meaning Example
Bitwise AND x & y = 0 ( )
Bitwise OR x | y = 14 ( )
Bitwise NOT ~x = -11 ( )
Bitwise XOR x ^ y = 14 ( )
Bitwise right shift x >> 2 = 2 ( )
Bitwise left shift x 0010 1000)

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.

Operator Meaning Example
if the operands are identical (refer to the same object)
if the operands are not identical (do not refer to the same object)

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.

Operator Meaning Example
if value/variable is in the sequence
if value/variable is in the sequence

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

Write a function to split the restaurant bill among friends.

  • Take the subtotal of the bill and the number of friends as inputs.
  • Calculate the total bill by adding 20% tax to the subtotal and then divide it by the number of friends.
  • Return the amount each friend has to pay, rounded off to two decimal places.

Video: Operators in Python

Sorry about that.

Related Tutorials

Python Tutorial

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:

Operator Name Example Try it
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3
print(x)

Advertisement

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example Try it
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example Try it
and  Returns True if both statements are true x < 5 and  x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

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
is not Returns True if both variables are not the same object x is not y

Python Membership Operators

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

Operator Description Example Try it
in  Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example Try it
AND Sets each bit to 1 if both bits are 1 x & y
| OR Sets each bit to 1 if one of two bits is 1 x | y
^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y
~ NOT Inverts all the bits ~x
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off x >> 2

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:

Operator Description Try it
Parentheses
Exponentiation
    Unary plus, unary minus, and bitwise NOT
      Multiplication, division, floor division, and modulus
  Addition and subtraction
  Bitwise left and right shifts
Bitwise AND
Bitwise XOR
Bitwise OR
                    Comparisons, identity, and membership operators
Logical NOT
AND
OR

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:

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.

Python Programming

Python Operators

Updated on:  November 14, 2021 | 33 Comments

Learning the operators is an excellent place to start to learn Python. Operators are special symbols that perform specific operations on one or more operands (values) and then return a result. For example, you can calculate the sum of two numbers using an addition ( + ) operator.

The following image shows operator and operands

Python operator and operands

  • Python If-else and Loops Exercise
  • Python Operators and Expression Quiz

Python has seven types of operators that we can use to perform different operation and produce a result.

Arithmetic operator

  • Relational operators

Assignment operators

Logical operators, membership operators, identity operators.

  • Bitwise operators

Table of contents

Addition operator +.

  • Subtraction –

Multiplication *

Floor division //, exponent **, relational (comparison) operators, and (logical and), or (logical or), not (logical not), in operator, not in operator, is operator, is not operator, bitwise and &, bitwise or |, bitwise xor ^.

  • Bitwise 1’s complement ~
  • Bitwise left-shift <<
  • Bitwise right-shift >>

Python Operators Precedence

Arithmetic operators are the most commonly used. The Python programming language provides arithmetic operators that perform addition, subtraction, multiplication, and division. It works the same as basic mathematics.

There are seven arithmetic operators we can use to perform different mathematical operations, such as:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • // Floor division)
  • ℅ (Modulus)
  • ** (Exponentiation)

Now, let’s see how to use each arithmetic operator in our program with the help of examples.

It adds two or more operands and gives their sum as a result. It works the same as a unary plus. In simple terms,  It performs the addition of two or more than two values and gives their sum as a result.

Also, we can use the addition operator with strings, and it will become string concatenation.

Subtraction -

Use to subtracts the second value from the first value and gives the difference between them. It works the same as a unary minus. The subtraction operator is denoted by - symbol.

Multiply two operands. In simple terms, it is used to multiplies two or more values and gives their product as a result. The multiplication operator is denoted by a * symbol.

You can also use the multiplication operator with string. When used with string, it works as a repetition.

Divide the left operand (dividend) by the right one (divisor) and provide the result (quotient ) in a float value. The division operator is denoted by a / symbol.

  • The division operator performs floating-point arithmetic. Hence it always returns a float value.
  • Don’t divide any number by zero. You will get a Zero Division Error: Division by zero

Floor division returns the quotient (the result of division) in which the digits after the decimal point are removed. In simple terms, It is used to divide one value by a second value and gives a quotient as a round figure value to the next smallest whole value.

It works the same as a division operator, except it returns a possible integer. The // symbol denotes a floor division operator.

  • Floor division can perform both floating-point and integer arithmetic.
  • If both operands are int type, then the result types. If at least one operand type, then the result is a float type.

The remainder of the division of left operand by the right. The modulus operator is denoted by a % symbol. In simple terms, the Modulus operator divides one value by a second and gives the remainder as a result.

Using exponent operator left operand raised to the power of right. The exponentiation operator is denoted by a double asterisk ** symbol. You can use it as a shortcut to calculate the exponential value.

For example, 2**3 Here 2 is multiplied by itself 3 times, i.e., 2*2*2 . Here the 2 is the base, and 3 is an exponent.

Relational operators are also called comparison operators. It performs a comparison between two values. It returns a boolean  True or False depending upon the result of the comparison.

Python has the following six relational operators.

Assume variable x holds 10 and variable y holds 5

Example
 (Greater than)It returns True if the left operand is greater than the right  
result is 
 (Less than)It returns True if the left operand is less than the right  
result is 
 (Equal to)It returns True if both operands are equal  
result is 
 (Not equal to)It returns True if both operands are equal  
result is 
 (Greater than or equal to)It returns True if the left operand is greater than or equal to the right  
result is 
 (Less than or equal to)It returns True if the left operand is less than or equal to the right  
result is 

You can compare more than two values also. Assume variable x holds 10, variable y holds 5, and variable z holds 2.

So print(x > y > z) will return True because x is greater than y, and y is greater than z, so it makes x is greater than z.

In Python, Assignment operators are used to assigning value to the variable. Assign operator is denoted by = symbol. For example, name = "Jessa" here, we have assigned the string literal ‘Jessa’ to a variable name.

Also, there are shorthand assignment operators in Python. For example, a+=2 which is equivalent to a = a+2 .

 (Assign) Assign 5 to variable  a = 5
 (Add and assign) Add 5 to a and assign it as a new value to  a = a+5
 (Subtract and assign) Subtract 5 from variable   and assign it as a new value to  a = a-5
 (Multiply and assign) Multiply variable   by 5 and assign it as a new value to  a = a*5
 (Divide and assign) Divide variable   by 5 and assign a new value to  a = a/5
 (Modulus and assign) Performs modulus on two values and assigns it as a new value to  a = a%5
 (Exponentiation and assign) Multiply   five times and assigns the result to  a = a**5
 (Floor-divide and assign) Floor-divide   by 5 and assigns the result to  a = a//5

Logical operators are useful when checking a condition is true or not. Python has three logical operators. All logical operator returns a boolean value True or False depending on the condition in which it is used.

 (Logical and)True if both the operands are Truea and b
 (Logical or)True if either of the operands is Truea or b
 (Logical not)True if the operand is Falsenot a

The logical and operator returns True if both expressions are True. Otherwise, it will return. False .

In the case of arithmetic values , Logical and always returns the second value ; as a result, see the following example.

The  logical or the operator returns a boolean  True if one expression is true, and it returns False if both values are false .

In the case of arithmetic values , Logical or it always returns the first value; as a result, see the following code.

The  logical not operator returns boolean True if the expression is false .

In the case of arithmetic values , Logical not always return False for nonzero value.

Python’s membership operators are used to check for membership of objects in sequence, such as string, list , tuple . It checks whether the given value or variable is present in a given sequence. If present, it will return True else False .

In Python, there are two membership operator  in  and  not in

It returns a result as True if it finds a given object in the sequence. Otherwise, it returns False .

Let’s check if the number 15 present in a given list using the in operator.

It returns True if the object is not present in a given sequence. Otherwise, it returns False

Use the Identity operator to check whether the value of two variables is the same or not. This operator is known as a reference-quality operator because the identity operator compares values according to two variables’ memory addresses.

Python has 2 identity operators is and is not .

The is operator returns Boolean True or False . It Return True if the memory address first value is equal to the second value. Otherwise, it returns False .

Here, we can use is() function to check whether both variables are pointing to the same object or not.

The is not the operator returns boolean values either True or False . It Return True if the first value is not equal to the second value. Otherwise, it returns False .

Bitwise Operators

In Python, bitwise operators are used to performing bitwise operations on integers. To perform bitwise, we first need to convert integer value to binary (0 and 1) value.

The bitwise operator operates on values bit by bit, so it’s called bitwise . It always returns the result in decimal format. Python has 6 bitwise operators listed below.

  • & Bitwise and
  • | Bitwise or
  • ^ Bitwise xor
  • ~ Bitwise 1’s complement
  • << Bitwise left-shift
  • >>  Bitwise right-shift

It performs  logical AND  operation on the integer value after converting an integer to a binary value and gives the result as a decimal value. It returns True only if both operands are True. Otherwise, it returns False .

Here, every integer value is converted into a binary value. For example, a =7 , its binary value is 0111, and b=4 , its binary value is 0100. Next we performed logical AND, and got 0100 as a result, similarly for a and c, b and c

Following diagram shows AND operator evaluation.

Python bitwise AND

It performs  logical OR  operation on the integer value after converting integer value to binary value and gives the result a decimal value. It returns  False  only if both operands are  True . Otherwise, it returns  True .

Here, every integer value is converted into binary. For example,  a =7 its binary value is 0111, and b=4 , its binary value is 0100, after logical OR, we got 0111 as a result. Similarly for  a  and  c ,  b and  c .

Python bitwise OR

It performs Logical XOR  ^  operation on the binary value of a integer and gives the result as a decimal value.

Example : –

Here, again every integer value is converted into binary. For example,  a =7  its binary value is 0111 and b=4 , and its binary value is 0100, after logical XOR we got 0011 as a result. Similarly for  a  and  c ,  b  and  c .

Python bitwise XOR

Bitwise 1’s complement  ~

It performs 1’s complement operation. It invert each bit of binary value and returns the bitwise negation of a value as a result.

Bitwise left-shift  <<

The left-shift  <<  operator performs a shifting bit of value by a given number of the place and fills 0’s to new positions.

Python bitwise left shift

Bitwise right-shift  >>

The left-shift  >>  operator performs shifting a bit of value to the right by a given number of places. Here some bits are lost.

Python bitwise right shift

In Python, operator precedence and associativity play an essential role in solving the expression. An expression is the combination of variables and operators that evaluate based on operator precedence.

We must know what the precedence (priority) of that operator is and how they will evaluate down to a single value. Operator precedence is used in an expression to determine which operation to perform first.

In the above example. 1st precedence goes to a parenthesis () , then for plus and minus operators. The expression will be executed as.

The following tables shows operator precedence highest to lowest.

1 (Highest) Parenthesis
2 Exponent
3 , , Unary plus, Unary Minus, Bitwise negation
4 , , , Multiplication, Division, Floor division, Modulus
5 , Addition, Subtraction
6 , Bitwise shift operator
7 Bitwise AND
8 Bitwise XOR
9 Bitwise OR
10 , , , , , Comparison
11 , , ,  Identity, Membership
12notLogical NOT
13andLogical AND
14 (Lowest)orLogical OR

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

assignment operators in python example

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

assignment operators in python example

😶 Operators

Python operators are the symbols that allow us to perform different types of operations on variables and values. They are the building blocks of any programming language, and Python is no exception. Python provides a wide range of operators that can be used to perform arithmetic, logical, comparison, assignment, and bitwise operations.

Understanding the different types of operators is crucial to writing efficient and error-free code in Python. In this section, we will explore the different types of operators available in Python and learn how to use them effectively in our programs. So buckle up and get ready to dive into the world of Python operators!

I. Arithmetic Operators

Arithmetic operators are used in Python to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and more. These operators are used on numeric data types such as integers, floats, and complex numbers.

Python provides the following arithmetic operators:

OperatorNameExampleResult

The floor division (//) operator returns the largest integer that is less than or equal to the division result.

a. Addition

Addition is one of the most basic arithmetic operations in Python. It is denoted by the + symbol and is used to add two numbers or concatenate two strings. For example, if we want to add two numbers x and y together, we can use the + operator like this:

Similarly, if we want to concatenate two strings a and b , we can use the + operator like this:

In both cases, the + operator performs the desired operation and returns a new value that we can assign to a variable or use directly.

b. Subtraction

The subtraction operator (-) is used to subtract one value from another. It takes two operands and returns the difference between them. For example, 5 - 3 will return 2, and 10.5 - 3.2 will return 7.3.

In Python, the subtraction operator can also be used with variables. For example:

Note that the subtraction operator can also be used with negative numbers. For example, 5 - (-3) will return 8.

c. Multiplication

Multiplication is a mathematical operation that is represented by the symbol * in Python. It is used to find the product of two or more values. Here's an example:

In the above example, we have two variables a and b with values 10 and 5 respectively. We multiply these two variables using the * operator and store the result in the variable c . Finally, we print the value of c which is 50 (the product of a and b ).

d. Division

In Python, the / operator is used for division. It returns the quotient (result of division) in the form of a float, even if both the operands are integers. If you want to get the quotient as an integer, you can use the // operator, which performs floor division.

Here's an example:

In the example above, we divide a by b using both the / and // operators. The result of the floating point division is stored in c , which is a float, while the result of the integer division is stored in d , which is an integer.

Modulus operator returns the remainder of the division operation between two operands. It is represented by the percentage sign % .

For example, the expression 9 % 4 returns 1 because when 9 is divided by 4, the remainder is 1.

Here is an example code snippet:

e. Exponentiation

Exponentiation is another arithmetic operator in Python represented by the double asterisk symbol (**). It raises the first operand to the power of the second operand.

Here, the base is the first operand, and the exponent is the second operand.

In the above example, 2 is raised to the power of 3, which results in 8.

f. Floor Division

Floor Division operator in Python is represented by two forward slashes // and it returns the quotient of the division operation rounding down to the nearest integer. For example, the floor division of 7 // 3 would be 2 since 3 goes into 7 two whole times with 1 left over.

Here's an example of using floor division operator:

In the above example, we have defined two variables a and b , and then used floor division operator // to divide a by b . Since a is 10 and b is 3 , the result of a // b is 3 .

II. Comparison Operators

Comparison operators, also known as relational operators, are used to compare two values or operands. In Python, comparison operators always return a boolean value - either True or False.

There are six comparison operators in Python:

Equal to (==)

Not equal to (!=)

Greater than (>)

Less than (<)

Greater than or equal to (>=)

Less than or equal to (<=)

These operators are used in conditional statements and loops to test whether a certain condition is true or false.

a. Equal to (==)

The equal to operator ( == ) is a comparison operator used to compare the equality of two operands. It returns True if the values of the two operands are equal, otherwise, it returns False .

In this example, the first comparison returns False because x is not equal to y . The second comparison returns True because x is equal to z .

b. Not equal to (!=)

In Python, the "not equal to" operator is represented by the exclamation mark followed by an equal sign (!=). It is a binary operator and is used to compare two values. The operator returns True if the values are not equal and False if they are equal.

Here's an example of using the "not equal to" operator in Python:

c. Greater than (>)

The greater than operator ( > ) is used to check if the left operand is greater than the right operand. It returns True if the left operand is greater than the right operand, otherwise, it returns False . Here is an example:

In the example above, x is greater than y , so the expression x > y returns True .

d. Less than (<)

In Python, the less than operator < is used to compare two operands. It returns True if the left operand is less than the right operand, and False otherwise.

In this example, x is less than y , so the if statement evaluates to True , and the first print statement is executed.

e. Greater than or equal to (>=)

The greater than or equal to operator (>=) is used to compare two values. It returns True if the left operand is greater than or equal to the right operand, and False otherwise.

For example:

In this example, the first print statement returns True because x (which is 5) is greater than or equal to y (which is 3). The second print statement returns False because y is less than x .

f. Less than or equal to (<=)

The "Less than or equal to" operator is represented by the symbol "<=". It is used to check if one value is less than or equal to another value.

For example, in the expression "5 <= 10", the operator "<=" checks if 5 is less than or equal to 10. Since this is true, the expression evaluates to True. However, in the expression "10 <= 5", the operator "<=" checks if 10 is less than or equal to 5. Since this is false, the expression evaluates to False.

Here's an example code snippet demonstrating the use of the "<=" operator:

This code will output "x is less than or equal to y", since 5 is indeed less than or equal to 10.

III. Logical Operators

Python Logical Operators are used to combine two or more conditions and perform logical operations on them. The following are the three logical operators in Python:

These operators are used to perform logical operations on the operands and return a Boolean value.

The 'and' operator returns True if both operands are True, otherwise, it returns False.

The 'or' operator returns True if either of the operands is True, otherwise, it returns False.

The 'not' operator returns the opposite of the operand.

Let's look at depth with some examples to understand how these operators work.

The and operator returns True if both operands are true and returns False if either one of the operands is false.

Here's the truth table for the and operator:

Operand 1Operand 2Result

Here's an example code snippet:

In this example, the and operator is used to check if x is smaller than both y and z . If this condition is true, then the statement "x is the smallest number" is printed.

The OR operator in Python is represented by or . It is a logical operator that returns True if at least one of the operands is True , and False otherwise. Here are the possible truth tables for the OR operator:

Operand 1Operand 2Result

Here's an example of using the OR operator in Python:

In this example, x is not greater than y or z , so the output will be x is not greater than y or z .

The NOT operator is a unary operator that negates the value of its operand. In Python, the NOT operator is represented by the keyword "not".

The NOT operator returns True if its operand is False, and vice versa. Here's an example:

In this example, the value of x is True. However, the NOT operator negates the value of x and returns False.

IV. Assignment Operators

Have you ever wanted to quickly assign or modify a value in Python without writing a lot of code? That's where assignment operators come in handy! They allow you to perform an operation on a variable and assign the result back to the same variable in a single step. In this section, we will explore the different types of assignment operators in Python.

a. Simple Assignment Operator

The simple assignment operator in Python is denoted by the equal sign "=" and is used to assign a value to a variable. The syntax for simple assignment is:

where variable is the name of the variable and value is the value to be assigned to the variable.

For example, the following code assigns the value 10 to the variable x :

After executing this code, the variable x will have the value 10 .

b. Arithmetic Assignment Operators

Arithmetic assignment operators are a shorthand way of performing arithmetic operations and assignment at the same time. These operators include:

+= : adds the value of the right operand to the value of the left operand and assigns the result to the left operand.

-= : subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

*= : multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.

/= : divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

%= : computes the modulus of the value of the left operand and the value of the right operand, and assigns the result to the left operand.

//= : performs floor division on the value of the left operand and the value of the right operand, and assigns the result to the left operand.

**= : raises the value of the left operand to the power of the value of the right operand, and assigns the result to the left operand.

These operators can be used with numeric values and variables of numeric types, such as integers and floating-point numbers.

In each of the above examples, the arithmetic operation and the assignment operation are performed at the same time using the shorthand arithmetic assignment operator.

c. Bitwise Assignment Operators

Bitwise assignment operators are used to perform a bitwise operation on a variable and then assign the result to the same variable. The bitwise assignment operators include:

&= : Performs a bitwise AND operation on the variable and the value on the right, then assigns the result to the variable.

|= : Performs a bitwise OR operation on the variable and the value on the right, then assigns the result to the variable.

^= : Performs a bitwise XOR operation on the variable and the value on the right, then assigns the result to the variable.

<<= : Performs a left shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

>>= : Performs a right shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

d. Logical Assignment Operators

There are no specific "Logical Assignment Operators" in Python, as the logical operators and , or , and not are already used for combining and negating boolean expressions. However, it is possible to use logical operators in combination with assignment operators to create compound expressions, such as x += y or z , which assigns the value of y to x if y is truthy, or the value of z otherwise.

e. Comparison Assignment Operators

There is no such thing as "Comparison Assignment Operators". The term "comparison operator" refers to operators that compare two values and return a boolean value (True or False), while "assignment operator" refers to operators that assign a value to a variable.

However, there are shorthand ways to perform a comparison and assign the result to a variable in a single line of code. For example:

x = 10 if a > b else 20 : This assigns the value 10 to x if a > b is True, otherwise it assigns the value 20.

x += 1 if a == b else 2 : This adds 1 to x if a == b is True, otherwise it adds 2.

x *= 2 if a < b else 3 : This multiplies x by 2 if a < b is True, otherwise it multiplies it by 3.

V. Bitwise Operators

Bitwise operators are used to manipulate the individual bits of binary numbers. In Python, bitwise operators can be applied to integers. The bitwise operators take two operands and operate on them bit by bit to produce a result. There are six bitwise operators in Python: AND, OR, XOR, NOT, left shift, and right shift. These operators are commonly used in low-level programming, such as device driver development and network packet processing.

a. Bitwise AND

The bitwise AND operator is represented by the & symbol in Python. It performs a logical AND operation on each corresponding bit of its operands. If both bits are 1, the resulting bit is 1. Otherwise, the resulting bit is 0.

In this example, a and b are two integers represented in binary. The & operator is used to perform a bitwise AND operation on the two numbers, resulting in the binary number 0010 , which is equivalent to the decimal number 2. The resulting value is assigned to the variable c .

b. Bitwise OR

Bitwise OR is another binary operator that operates on two integers and performs a bitwise OR operation on their binary representations. The resulting binary representation is converted back to an integer.

The syntax for the bitwise OR operator is the pipe symbol | . For example, a | b performs a bitwise OR operation on a and b .

In the above example, the binary OR operation on a and b results in 0011 1101 , which is equal to 61 in decimal representation.

c. Bitwise XOR

Bitwise XOR (exclusive OR) operator is represented by the symbol ^ in Python. The operator returns a binary number that has a 1 in each bit position where the corresponding bits of either but not both operands are 1.

For example, let's say we have two variables a = 13 and b = 17 . The binary representation of 13 is 1101 and the binary representation of 17 is 10001 . Now, let's perform the bitwise XOR operation on these two variables:

In the above example, the resulting binary number is 11000 , which is equivalent to the decimal number 24 . Therefore, the value of the variable c will be 24 .

Here is another example that demonstrates the use of bitwise XOR:

In this example, we first define a and b as binary numbers using the 0b prefix. We then perform the bitwise XOR operation on these two numbers and store the result in c . The resulting binary number is 0b110 , which is equivalent to the decimal number 6 . Therefore, the value of the variable c will be 6 .

d. Bitwise NOT

Bitwise NOT is a unary operator in Python that flips the bits of a number. It is represented by the tilde (~) symbol. When applied to a binary number, the Bitwise NOT operator returns the complement of the number.

In the above code, the value of x is 7, which is represented in binary as 0000 0111. When we apply the Bitwise NOT operator (~) to x , it flips all the bits of the number, resulting in 1111 1000. The output is in two's complement form, which is the way negative numbers are represented in binary.

VI. Membership Operators

Membership operators are used to test if a sequence is present in an object. In Python, we have two membership operators:

in : Evaluates to True if the sequence is present in the object.

not in : Evaluates to True if the sequence is not present in the object.

These operators are typically used with strings, lists, tuples, and sets to check if a certain element or a sequence of elements is present in them.

VII. Identity Operators

Identity Operators are used to compare the memory locations of two objects. There are two identity operators in Python:

is - Returns True if both variables are the same object.

is not - Returns True if both variables are not the same object.

In this example, x and y have the same values, but they are not the same object. z is assigned the same memory location as x , so x and z are the same object. The is operator returns True when comparing x and z , but False when comparing x and y . The is not operator returns False when comparing x and z , but True when comparing x and y .

Last updated 1 year ago

Table of Contents

Assignment operator, addition assignment operator, subtraction assignment operator, multiplication assignment operator, division assignment operator, modulus assignment operator, floor division assignment operator, exponentiation assignment operator, bitwise and assignment operator, bitwise or assignment operator, bitwise xor assignment operator , bitwise right shift assignment operator, bitwise left shift assignment operator, walrus operator, conclusion , python assignment operator: tips and tricks to learn.

Assignment Operators in Python

Assignment operators are vital in computer programming because they assign values to variables. Python stores and manipulates data with assignment operators like many other programming languages . First, let's review the fundamentals of Python assignment operators so you can understand the concept.

In Python, the following operators are often used for assignments:

Sign Type of Python Operators = Assignment Operator += Addition assignment -= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment //= Floor division assignment **= Exponentiation assignment &= Bitwise AND assignment |= Bitwise OR assignment ^= Bitwise XOR assignment >>= Bitwise right shift assignment <<= Bitwise left shift assignment := Walrus Operator

Python uses in-fix assignment operators to perform operations on variables or operands and assign values to the operand on the left side of the operator. It carries out calculations involving arithmetic, logical, and bitwise operations.

Python assignment operator provides a way to define assignment statements. This statement allows you to create, initialize, and update variables throughout your code, just like a software engineer . Variables are crucial in any code; assignment statements provide complete control over creating and modifying variables.

Understanding the Python assignment operator and how it is used in assignment statements can equip you with valuable tools to enhance the quality and reliability of your Python code.

In Python, the equals sign (=) is the primary assignment operator. It assigns the variable's value on the left side to the value on the right side of the operator.

Here's a sample to think about:

In this code snippet, the variable 'x' is given the value of 6. The assignment operator doesn't check for equality but assigns the value.

Become a Online Certifications Professional

  • 13 % CAGR Estimated Growth By 2026
  • 30 % Increase In Job Demand

Python Training

  • 24x7 learner assistance and support

Automation Testing Masters Program

  • Comprehensive blended learning program
  • 200 hours of Applied Learning

Here's what learners are saying regarding our programs:

Charlotte Martinez

Charlotte Martinez

This is a good course for beginners as well as experts with all the basic concepts explained clearly. It's a good starter to move to python programming for programmers as well as non- programmers

Daniel Altufaili

Daniel Altufaili

It infrastructure oprations , johnson electric.

Upon finishing the QA automation course, I received fresh assignments at my job owing to my heightened proficiency in IT, IoT, and ML. In addition to this, I earned a promotion and 20% salary increase. This course significantly expanded my expertise and motivated me to continuously enhance my skills through ongoing upskilling efforts.

The addition assignment operator (+=) adds the right-hand value to the left-hand variable.

The addition assignment operator syntax is variable += value.

The addition assignment operator increments a by 5. The console displays 14 as the result.

Also Read: Top Practical Applications of Python

The subtraction assignment operator subtracts a value from a variable and stores it in the same variable.

The subtraction assignment operator syntax is variable-=-value.

Using the multiplication assignment operator (=), multiply the value on the right by the variable's existing value on the left.

The assignment operator for multiplication has the following syntax: variable *= value

In this situation, the multiplication assignment operator multiplies the value of a by 2. The output, 10, is shown on the console.

Related Read: 16 Most Important Python Features and How to Use them

Using the division assignment operator (/=), divide the value of the left-hand variable by the value of the right-hand variable.

The assignment operator for division has the following syntax: variable /= value

Using the division assignment operator, divide a value by 3. The console displays 5.0.

Recommended Read: Why Choose Python? Discover Its Core Advantages!

The modulus assignment operator (% =) divides the left and right variable values by the modulus. The variable receives the remainder.

The modulus assignment operator syntax is variable %= value.

The modulus assignment operator divides a by 2. The console displays the following: 1.

Use "//" to divide and assign floors in one phrase. What "a//=b" means is "a=a//b". This operator cannot handle complicated numbers.

The floor division assignment operator syntax is variable == value.

The floor division assignment operator divides a by 2. The console displays 5.

The exponentiation assignment operator (=) elevates the left variable value to the right value's power.

Operator syntax for exponentiation assignment:

variable**=value

The exponentiation assignment operator raises a to 2. The console shows 9.

The bitwise AND assignment operator (&=) combines the left and right variable values using a bitwise AND operation. Results are assigned to variables.

The bitwise AND assignment operator syntax is variable &= value.

The bitwise AND assignment operator ANDes a with 2. The console displays 2 as the outcome.

The bitwise OR assignment operator (|=) bitwise ORs the left and right variable values.

The bitwise OR assignment operator syntax is variable == value.

A is ORed with 4 using the bitwise OR assignment operator. The console displays 6.

Use the bitwise XOR assignment operator (^=) to XOR the left and right values of a variable. Results are assigned to variables.

For bitwise XOR assignment, use the syntax: variable ^= value.

The bitwise XOR assignment operator XORs a with 4. The console displays 2 as the outcome.

The right shift assignment operator (>>=) shifts the variable's left value right by the number of places specified on the right.

The assignment operator for the bitwise right shift has the following syntax:

variable >>= value

The bitwise right shift assignment operator shifts 2 places to the right. The result is 1.

The variable value on the left moves left by the specified number of places on the right using the left shift assignment operator (<<=).

The bitwise left shift assignment operator syntax is variable <<= value.

When we execute a Bitwise right shift on 'a', we get 00011110, which is 30 in decimal.

Python gets new features with each update. Emily Morehouse added the walrus operator to Python 3.8's initial alpha. The most significant change in Python 3.8 is assignment expressions. The ":=" operator allows mid-expression variable assignment. This operator is called the walrus operator.

variable := expression

It was named for the operator symbol (:=), which resembled a sideways walrus' eyes and tusks.

Walrus operators simplify code authoring, which is its main benefit. Each user input was stored in a variable before being passed to the for loop to check its value or apply a condition. It is important to note that the walrus operator cannot be used alone.

With the walrus operator, you can simultaneously define a variable and return a value.

Above, we created two variables, myVar and value, with the phrase myVar = (value = 2346). The expression (value = 2346) defines the variable value using the walrus operator. It returns the value outside the parenthesis as if value = 2346 were a function. 

The variable myVar is initialized using the return value from the expression (value = 2346). 

The output shows that both variables have the same value.

Learn more about other Python operators by reading our detailed guide here .

Discover how Python assignment operators simplify and optimize programs. Python assignment operators are explained in length in this guide, along with examples, to help you understand them. Start this intriguing journey to improve your Python knowledge and programming skills with Simplilearn's Python training course .

1. What is the ":=" operator in Python?

Python's walrus operator ":" evaluates, assigns, and returns a value from a single sentence. Python 3.8 introduces it with this syntax (variable:=expression).

2. What does = mean in Python?

The most significant change in Python 3.8 is assignment expressions. The walrus operator allows mid-expression variable assignment.

3. What is def (:) Python?

The function definition in Python is (:). Functions are defined with def. A parameter or parameter(s) follows the function name. The function body begins with an indentation after the colon (:). The function body's return statement determines the value.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees

Cohort Starts:

4 Months€ 2,499

Cohort Starts:

11 Months€ 1,099

Cohort Starts:

6 Months€ 1,500

Cohort Starts:

6 Months€ 1,500

Recommended Reads

Python Interview Guide

Filter in Python

Understanding Python If-Else Statement

Top Job Roles in the Field of Data Science

Yield in Python: An Ultimate Tutorial on Yield Keyword in Python

The Best Tips for Learning Python

Get Affiliated Certifications with Live Class programs

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • Python Course
  • 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

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. So assume if we need to add 7 to a variable “a” and assign the result back to “a”, then instead of writing normally as “ a = a + 7 “, we can use the augmented assignment operator and write the expression as “ a += 7 “. Here += has combined the functionality of arithmetic addition and assignment.

So, augmented assignment operators provide a short way to perform a binary operation and assigning results back to one of the operands. The way to write an augmented operator is just to write that binary operator and assignment operator together. In Python, we have several different augmented assignment operators like +=, -=, *=, /=, //=, **=, |=, &=, >>=, <<=, %= and ^=. Let’s see their functioning with the help of some exemplar codes:

1. Addition and Assignment (+=): This operator combines the impact of arithmetic addition and assignment. Here,

 a = a + b can be written as a += b

2. Subtraction and Assignment (-=): This operator combines the impact of subtraction and assignment.  

a = a – b can be written as a -= b

Example:  

3. Multiplication and Assignment (*=): This operator combines the functionality of multiplication and assignment.  

a = a * b can be written as a *= b

4. Division and Assignment (/=): This operator has the combined functionality of division and assignment.  

a = a / b can be written as a /= b

5. Floor Division and Assignment (//=): It performs the functioning of floor division and assignment.  

a = a // b can be written as a //= b

6. Modulo and Assignment (%=): This operator combines the impact of the modulo operator and assignment.  

a = a % b can be written as a %= b

7. Power and Assignment (**=): This operator is equivalent to the power and assignment operator together.  

a = a**b can be written as a **= b

8. Bitwise AND & Assignment (&=): This operator combines the impact of the bitwise AND operator and assignment operator. 

a = a & b can be written as a &= b

9. Bitwise OR and Assignment (|=): This operator combines the impact of Bitwise OR and assignment operator.  

a = a | b can be written as a |= b

10. Bitwise XOR and Assignment (^=): This augmented assignment operator combines the functionality of the bitwise XOR operator and assignment operator. 

a = a ^ b can be written as a ^= b

11. Bitwise Left Shift and Assignment (<<=): It puts together the functioning of the bitwise left shift operator and assignment operator.  

a = a << b can be written as a <<= b

12. Bitwise Right Shift and Assignment (>>=): It puts together the functioning of the bitwise right shift operator and assignment operator.  

a = a >> b can be written as a >>= b

Please Login to comment...

Similar reads.

  • School Learning
  • School Programming
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Javatpoint Logo

Python Tutorial

Python oops, python mysql, python mongodb, python sqlite, python questions, python tkinter (gui), python web blocker, related tutorials, python programs.

JavaTpoint

In this section, we will discuss the assignment operators in the Python programming language. Before moving on to the topic, let's give a brief introduction to operators in Python. are special symbols used in between operands to perform logical and mathematical operations in a programming language. The value on which the operator operates the computation is called the . There are different types of arithmetic, logical, relational, assignment, and bitwise, etc.

has an that helps to assign values or expressions to the left-hand-side variable. The assignment operator is represented as the "=" symbol used in assignment statements and assignment expressions. In the assignment operator, the right-hand side value or operand is assigned to the left-hand operand.

Following are the examples of the assignment operators:

Following are the different types of assignment operators in Python:

A simple assignment operator assigns the right side operand expression or value to the left side operand.

An operator adds the right side operand or value to the left operand before assigning the result to the left operand.

An operator subtracts the right side operand or value from the left operand and stores the value to the left operand.

An operator multiplies the right side operand or value to the left operand and stores the product to the left operand.

An operator divides the left operand by the right operand before assigning the result to the left operand.

An operator divides the left operand by the right side operand or value and places the remainder to the left side operand.

A floor division operator divides the left operand by the right side operand or value and then assigns floor (value) to the left operand.

An exponent assign operator is used to get the exponent value using both operands and assign the result into the left operand.

A Bitwise And (&) and assigns operator is used to operate on both (left and right) operands and assign results into the left operand.

A Bitwise OR and Assignment operator is used to operate on both (left and right) operand and store results into the left operand.

A Bitwise XOR and Assignment operator operated on both (left and right) operand and assign the results into the left operand.

An operator shifts the specified amount of bits or operands to the right and assigns value to the left operand.

An operator shifts the specified amount of operands to the left side and assigns the result to the left operand.





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

IMAGES

  1. Python Tutorials: Assignment Operators In python

    assignment operators in python example

  2. Assignment Operators in Python

    assignment operators in python example

  3. Python Operators

    assignment operators in python example

  4. Assignment operators in python

    assignment operators in python example

  5. Python Operator

    assignment operators in python example

  6. Python Operators

    assignment operators in python example

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 Operators - The = (equal to) symbol is defined as assignment operator in Python. ... Example. 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:

  5. Assignment Operators in Python

    Assignment Operators in Python are used to assign values to the variables. "=" is the fundamental Python assignment operator. The value on the right side of the "=" is assigned to the variable on the left side of "=". In this Python tutorial, we'll understand Python programming assignment operators with examples and augmented assignment operators in Python.

  6. Python Assignment Operators

    Login to Save. 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)

  7. Python Assignment Operators: A Beginner's Guide with Examples

    Python offers a variety of tools to manipulate and manage data. Among these are assignment operators, which enable programmers to assign values to variables in a concise and efficient manner. Whether you're a newcomer to programming or just getting started with Python, understanding assignment operators is a fundamental step toward becoming a proficient coder. In […]

  8. Python Assignment Operators

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

  9. Assignment Operators in Python

    a /= b. %=. Divide AND will divide the left operand with the right operand and then assign to the left operand. a %= b. <<=. It functions bitwise left on operands and will assign value to the left operand. a <<= b. >>=. This operator will perform right shift on operands and can assign value to the left operand.

  10. Operators and Expressions in Python

    In Python, operators are special symbols, combinations of symbols, or keywords that designate some type of computation. You can combine objects and operators to build expressions that perform the actual computation. ... You'll use the assignment operator in many of the examples that you'll write throughout this tutorial. More importantly ...

  11. Python Assignment Operators

    The Python Assignment Operators are handy for assigning the values to the declared variables. Equals (=) is the most commonly used assignment operator in Python. For example: i = 10. The list of available assignment operators in Python language. Python Assignment Operators. Example. Explanation. =.

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

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

  14. The Walrus Operator: Python's Assignment Expressions

    Each new version of Python adds new features to the language. Back when Python 3.8 was released, the biggest change was the addition of assignment expressions.Specifically, the := operator gave you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.. This tutorial is an in-depth introduction to the walrus operator.

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

  16. Assignment Operators in Python

    Demonstrating Python Assignment Operators Through Examples Python assignment operators can be demonstrated with practical examples: `x += 5` adds 5 to the current value of `x`, while `x -= 3` subtracts 3 from `x`. Multiplication and exponentiation are performed with `x *= 2` and `x **= 2`, respectively. Division, floor division, and modulus are ...

  17. How to Use Assignment Operators in Python

    If that is about as clear as mud don't worry we're going to walk through a number of examples. And one very nice thing about the syntax for assignment operators is that it is nearly identical to a standard type of operator. So if you memorize the list of all the python operators then you're going to be able to use each one of these assignment ...

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

  19. Python Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator Example Same As Try it = x = 5: x = 5: ... Operator Description Example Try it; in : Returns True if a sequence with the specified value is present in the object: x in y:

  20. Python Operators

    In Python, Assignment operators are used to assigning value to the variable. Assign operator is denoted by = symbol. ... we have assigned the string literal 'Jessa' to a variable name. Also, there are shorthand assignment operators in Python. For example, a+=2 which is equivalent to a = a+2. Operator Meaning Equivalent = (Assign) a=5Assign ...

  21. Operators

    In this example, the and operator is used to check if x is smaller than both y and z. If this condition is true, then the statement "x is the smallest number" is printed. ... There are no specific "Logical Assignment Operators" in Python, as the logical operators and, or, and not are already used for combining and negating boolean expressions ...

  22. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  23. Python Assignment Operator: A Comprehensive Guide 2024!

    Discover how Python assignment operators simplify and optimize programs. Python assignment operators are explained in length in this guide, along with examples, to help you understand them. Start this intriguing journey to improve your Python knowledge and programming skills with Simplilearn's Python training course. FAQs 1.

  24. Augmented Assignment Operators 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. Operators Sign Description SyntaxAssignment Operator = Assi

  25. Assignment Operators in Python

    The assignment operator is represented as the "=" symbol used in assignment statements and assignment expressions. In the assignment operator, the right-hand side value or operand is assigned to the left-hand operand. Following are the examples of the assignment operators: