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

Python Assignment Operators

Assignment operators in python.

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

Python Relational Operators

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

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

Operators

=

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


+=

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

-=

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


*=

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


/=

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


%=

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


//=

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


**=

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


&=

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


|=

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


^=

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


>>=

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


<<=

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


:=

Assign a value to a variable within an expression

a := exp

Here are the Assignment Operators in Python with examples.

Assignment Operator

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

Addition Assignment Operator

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

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

S ubtraction Assignment Operator

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

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

M ultiplication Assignment Operator

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

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

D ivision Assignment Operator

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

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

M odulus Assignment Operator

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

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

F loor Division Assignment Operator

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

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

Exponentiation Assignment Operator

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

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

Bitwise AND Assignment Operator

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

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

Bitwise OR Assignment Operator

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

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

Bitwise XOR Assignment Operator 

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

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

Bitwise Right Shift Assignment Operator

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

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

Bitwise Left Shift Assignment Operator

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

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

Walrus Operator

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

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

author

Please Login to comment...

Similar reads.

  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

python and assignment operator

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

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

Python 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:

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

The Walrus Operator: Python 3.8 Assignment Expressions

The Walrus Operator: Python 3.8 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. For Python 3.8, the biggest change is the addition of assignment expressions . Specifically, the := operator gives 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 will learn some of the motivations for the syntax update and explore some 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
  • Understand the impacts on backward compatibility when using the walrus operator
  • Use appropriate style in your assignment expressions

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

Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

Walrus Operator Fundamentals

Let’s start with 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 sideways walrus . 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 seen earlier 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, while it 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.

Note: You need at least Python 3.8 to try out the examples in this tutorial. If you don’t already have Python 3.8 installed and you have Docker available, a quick way to start working with Python 3.8 is to run one of the official Docker images :

This will download and run the latest stable version of Python 3.8. For more information, see Run Python Versions in Docker: How to Try the Latest Python Release .

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, as well as 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) . Starting in early 2019, Python 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 function as expressions. This can be both very powerful and also 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 raises 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 = is not 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 is not allowed, but first you’ll learn about the situations where you might want to use them.

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 7200 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 is 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 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 did not 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 was 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, this role can be made more clear:

num_length and num_sum are now defined 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 6 loops over each filename provided by the user. sys.argv is a list containing 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 7 translates 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 8 to 12 construct a tuple of counts to represent the number of lines, words, and characters in one text file.
  • Line 9 reads a text file and calculates the number of lines by counting newlines.
  • Line 10 reads a text file and calculates the number of words by splitting on whitespace.
  • Line 11 reads a text file and calculates the number of characters by finding the length of the string.
  • Line 13 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 13 lines, 34 words, and 316 characters.

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

The contents of the file are assigned to text , which is reused in the next two calculations. The program still functions the same:

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, the 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 can instead be performed 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, readable, and 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 will not work:

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

Let’s 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 installing both into your virtual environment :

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 .

Let’s 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 help you keep your code readable while you avoid 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 only about the podcast. 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 list comprehensions can be rewritten 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 used when you don’t know beforehand how many times you’ll need to 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 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 often be used to 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. 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!

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’s made possible by this new operator.

In this section, you’ll learn how you can find witnesses when calling any() by using a clever trick that isn’t 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 "H" ?

Yes, because "Houston" starts with "H" .

Do all city names start with "H" ?

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

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 "H" . Then, if there’s at least one such city name, you print out the first city name starting with "H" . 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 "H" , 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 see what’s happening more clearly by wrapping .startswith("H") in a function that also prints out which item is being checked:

Note that any() doesn’t actually check all 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. 'Holguín' doesn’t contain ten or more characters. The witness only shows which item happened to be evaluated last.

One of the main reasons assignments were not expressions in Python from the beginning is that the visual likeness of the assignment operator ( = ) and the equality comparison operator ( == ) could potentially lead to bugs. When introducing assignment expressions, a lot of thought was put 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 only if you add parentheses:

Even though it’s possible, however, this really 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 raise 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 , a colon ( : ) is used 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.

Let’s 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, it will be interpreted 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 will behave similarly to traditional assignment statements in many respects:

The scope of the assignment target is the same as for assignments. It will 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 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 is assigned. 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, it would not 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 are not needed.

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

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

If you need to support older versions of Python, you can’t ship code that uses assignment expressions. There are some projects, like walrus , that can automatically translate walrus operators into code that is compatible with older versions of Python. This allows you to take advantage of assignment expressions when writing your code and still distribute code that is compatible with more Python versions.

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

There are many times it’s possible for you to use the walrus operator, but where 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 new 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 will only help you in some 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:

Python Tricks: The Book

"Python Tricks: The Book" – Free Sample Chapter (PDF)

🔒 No spam. We take your privacy seriously.

python and assignment operator

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • 10 Python Developer Skills you must know in 2024
  • Python Developer Roadmap: How to become a Python Developer?
  • How to Become a Python Full Stack Developer [Step-by-Step]
  • Python Career Guide: Is it worth learning in 2024?
  • Top 50+ Python Interview Questions and Answers
  • Python Developer Salary

02 Beginner

  • Python For Loop
  • Difference between For Loop and While Loop in Python
  • Bitwise Operators in Python
  • Logical Operators Python
  • Comparison Operators Python
  • Understanding Python While Loop with Examples
  • Factorial Calculator in Python
  • The map() Function in Python
  • Calculation of Armstrong Number in Python
  • Program to Check Leap Year in Python
  • The enumerate() Function in Python
  • How to Run a Python Script- A Step by Step Guide
  • Python Program to Check Prime Number
  • Lambda() Function in Python
  • Fibonacci Series in Python
  • Python Features: A Comprehensive Guide for Beginners
  • Data Structures in Python - Types and Examples (A Complete Guide)
  • List of Python Keywords (With Examples)
  • Python Membership Operators: Types of Membership Operators

Assignment Operators in Python

  • Arithmetic Operators in Python
  • Addition of Two Numbers in Python
  • What is a Python Interpreter?
  • Understanding Constructors in Python
  • Introduction to the python language
  • What is Python Language? Overview of the Python Language
  • Python Basic Syntax: First Python Program
  • Comments in Python: An Overview
  • What are Python Variables - Types of Variables in Python Language
  • Data Types in Python - 8 Data Types in Python With Examples
  • What are Operators in Python - Types of Operators in Python ( With Examples )
  • Decision Making Statements: If, If..else, Nested If..else and if-elif-else Ladder
  • Types of Loops in Python - For, While Loop
  • 10 Reasons Python is a Great First Language to Learn
  • Tuples in Python with Examples - A Beginner Guide
  • Python Functions: A Complete Guide

03 Intermediate

  • Python Classes and Objects with Examples
  • How to Use List Comprehension in Python
  • OOPs Concepts in Python
  • What are Strings in Python? Learn to Implement Them.
  • Python Lists: List Methods and Operations
  • Python Dictionaries (With Examples) : A Comprehensive Tutorial
  • Modules in Python
  • Exception Handling in Python: Try and Except Statement

04 Training Programs

  • Java Programming Course
  • MERN: Full-Stack Web Developer Certification Training
  • Data Structures and Algorithms Training
  • Assignment Operators In P..

Assignment Operators in Python

What is an Assignment Operator in Python?

Assignment Operators in Python are used to assign values to the variables. "=" is the fundamental Python assignment operator. They require two operands to operate upon. The left side operand is called a variable, and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=". The associativity is from right to left.

Types of Assignment Operators in Python

1. Augmented Arithmetic Assignment Operators in Python

There are seven combinations of arithmetic operators with the assignment operator "=." The below table gives a glimpse of them.

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

We'll see all these operators in detail in the upcoming sections.

2. Augmented Bitwise Assignment Operators in Python

There are five combinations of bitwise operators with the assignment operator "=." The below table gives a glimpse of them.

&=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 (+=).

It adds the right operand to the left operand and assigns the result to the left operand.

Example of Augmented Addition Operator in Python

In this example, we have assigned the value of the sum of x and y to the variable x using the assignment operator (+=).

2. Augmented Subtraction Operator (-=)

It subtracts the right operand from the left operand and assigns the result to the left operand.

Example of Augmented Subtraction Operator in Python

In this example, we have assigned the value of the difference between x and y to the variable x using the assignment operator (-=).

3. Augmented Multiplication Operator (*=)

It multiplies the right operand with the left operand and assigns the result to the left operand.

Example of Augmented Multiplication Operator in Python

In this example, we have assigned the value of the product of x and y to the variable x using the assignment operator (*=).

4. Augmented Division Operator (/=)

It divides the left operand with the right operand and assigns the result to the left operand.

Example of Augmented Division Operator in Python

In this example, we have assigned the value of the result of dividing x by y to the variable x using the assignment operator (/=).

5. Augmented Modulus Operator (%=)

It calculates the modulus of two operands and assigns the result to the left operand.

Example of Augmented Modulus Operator in Python

In this example, we have assigned the value of the modulus of x by y to the variable x using the assignment operator (%=).

6. Augmented Floor division Operator (//=)

It divides the left operand with the right operand and assigns the floor value to the left operand.

Example of Augmented Floor Division Operator in Python

In this example, we have assigned the floor value of the division of x by y to the variable x using the assignment operator (//=).

7. Augmented Exponent Operator (**=)

It calculates the exponent(raise power) value of the left operand raised to the right operand and assigns the floor value to the left operand.

Example of Augmented Exponent Operator in Python

In this example, we have assigned the exponent value of x raised to y to the variable x using the assignment operator (**=).

Augmented Bitwise Assignment Operators in Python

1. augmented bitwise and (&=).

It performs the bitwise AND operation on the left and right operands and assigns the result to the left operand.

Example of Augmented Bitwise AND Operator in Python

In this example, we have assigned the result of x & y to the variable x using the assignment operator (&=).

2. Augmented Bitwise OR (|=)

It performs the bitwise OR operation on the left and right operands and assigns the result to the left operand.

Example of Augmented Bitwise OR Operator in Python

In this example, we have assigned the result of x | y to the variable x using the assignment operator (|=).

3. Augmented Bitwise XOR (^=)

It performs the bitwise XOR operation on the left and right operands and assigns the result to the left operand.

Example of Augmented Bitwise XOR Operator in Python

In this example, we have assigned the result of x ^ y to the variable x using the assignment operator (^=).

4. Augmented Bitwise Right Shift (>>=)

It performs the bitwise right shift operation on the left and right operands and assigns the result to the left operand.

Example of Augmented Bitwise Right Shift Operator in Python

In this example, we have assigned the result of x >>= y to the variable x using the assignment operator (>>=).

5. Augmented Bitwise Left Shift (<<=)

It performs the bitwise left shift operation on the left and right operands and assigns the result to the left operand.

Example of Augmented Bitwise Left Shift Operator in Python

In this example, we have assigned the result of x <<= y to the variable x using the assignment operator (<<=).

Walrus Operator in Python

Python 3.8 introduced the walrus operator (:=) to write an assignment expression. Assignment expressions have a return value that is automatically assigned to a variable.

Syntax of an Assignment Expression

Example of walrus operator in python.

The ":=" operator assigns the value of numbers.pop(0) to the variable num and evaluates it in the Python while loop condition.

Assignment operators are critical fundamental operators that are useful for various operations. They are capable of performing assignment, bitwise, and shift operations. To learn Python effectively, you need to master these operators.

Live Classes Schedule

Generative AI For Software Developers Jul 20 SAT, SUN Filling Fast
Angular Certification Course Jul 20 SAT, SUN Filling Fast
Azure Master Class Jul 20 SAT, SUN Filling Fast
ASP.NET Core Certification Training Jul 28 SAT, SUN Filling Fast
Software Architecture and Design Training Jul 28 SAT, SUN Filling Fast
.NET Solution Architect Certification Training Jul 28 SAT, SUN Filling Fast
Azure Developer Certification Training Jul 28 SAT, SUN Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN Filling Fast
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN Filling Fast
Angular Certification Course Aug 11 SAT, SUN Filling Fast
ASP.NET Core Project Aug 24 SAT, SUN Filling Fast

Can't find convenient schedule? Let us know

About Author

Author image

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Java Programming Course

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

logo

Python Assignment Operators

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

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

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

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

Here are some examples of using compound assignment operators:

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

IMAGES

  1. Python Operators and Expressions

    python and assignment operator

  2. Python Operator

    python and assignment operator

  3. A Handy Guide to Python

    python and assignment operator

  4. Python Cheat Sheet for Leetcode

    python and assignment operator

  5. Operators in Python

    python and assignment operator

  6. Python Operators

    python and assignment operator

VIDEO

  1. Assignment

  2. Belajar Python with Visual Studio

  3. python Assignment operator #shorts #python #assignment #operator #print #coding #programming

  4. python Assignment operator #shorts #python #assignment #operator #print# #coding #programming

  5. Python Assignment Operator #coding #assignmentoperators #phython

  6. python Assignment operator #shorts #python #assignment #operator #coding #programming

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

    In this tutorial, you'll learn how to use Python's assignment operators to write assignment statements that allow you to create, initialize, and update variables in your code.

  2. Assignment Operators in Python - GeeksforGeeks

    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.

  3. Python Assignment Operators - W3Schools

    Python Assignment Operators. Assignment operators are used to assign values to variables:

  4. Python Assignment Operators - Educative

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

  5. Python Operators: Arithmetic, Assignment, Comparison, Logical ...

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

  6. Python Operators - W3Schools

    Python Assignment Operators. Assignment operators are used to assign values to variables: Python Comparison Operators. Comparison operators are used to compare two values: Python Logical Operators. Logical operators are used to combine conditional statements: Python Identity Operators.

  7. The Walrus Operator: Python 3.8 Assignment Expressions

    In this tutorial, you'll learn about assignment expressions and the walrus operator. The biggest change in Python 3.8 was the inclusion of the := operator, which you can use to assign variables in the middle of expressions. You'll see several examples of how to take advantage of this new feature.

  8. Assignment Operators in Python

    What is an Assignment Operator in Python? Assignment Operators in Python are used to assign values to the variables. "=" is the fundamental Python assignment operator. They require two operands to operate upon. The left side operand is called a variable, and the right side operand is the value.

  9. Python Assignment Operators - PythonHello

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

  10. Python Assignment Operators - NetworkLessons.com

    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 .