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.

assignment operator python example

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 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 Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Questions & Answers
  • Python - Online Quiz
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python Assignment Operator

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

Example of Assignment Operator in Python

Consider following Python statements −

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

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

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

Augmented Assignment Operators in Python

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

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

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

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

The following are the augmented assignment operators in Python:

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

Augmented Addition Operator (+=)

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

It will produce the following output −

Augmented Subtraction Operator (-=)

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

Augmented Multiplication Operator (*=)

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

Augmented Division Operator (/=)

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

Augmented Modulus Operator (%=)

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

Augmented Exponent Operator (**=)

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

Augmented Floor division Operator (//=)

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

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

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

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:

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

About Author

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

Assignment operators ​.

Assignment operators are used to assign values to variables.

There are various compound operators in Python.

For example, a += 2 adds 2 to the variable and then assigns it to the variable. It is equivalent to a = a + 2 .

OperatorDescriptionExampleEquivalent to
Assign value of right side of expression to left side operand
Add right-side operand with left side operand and then assign to left operand
Subtract right operand from left operand and then assign to left operand
Multiply right operand with left operand and then assign to left operand
Divide left operand with right operand and then assign to left operand
Takes modulus using left and right operands and assign the result to left operand
Divide left operand with right operand and then assign the value(floor) to left operand
Calculate exponent(raise power) value using operands and assign value to left operand
Performs Bitwise AND on operands and assign value to left operand
Performs Bitwise OR on operands and assign value to left operand
Performs Bitwise XOR on operands and assign value to left operand
Performs Bitwise right shift on operands and assign value to left operand
Performs Bitwise left shift on operands and assign value to left operand

Add and Assign ​

Subtract and assign ​, multiply and assign ​, divide and assign ​, modulus and assign ​, divide (floor) and assign ​, exponent and assign ​, bitwise and and assign ​, bitwise or and assign ​, bitwise xor and assign ​, bitwise right shift and assign ​, bitwise left shift and assign ​, table of contents.

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Python Programming
  • Python Tutorial
  • Python Variables
  • Python Datatypes
  • Python Comments
  • Python – If
  • Python – If Else
  • Python – Elif
  • Python While Loop
  • Python For Loop
  • Python While Loop with Multiple Conditions
  • Python While Loop with Break
  • Python While Loop with Continue
  • Python Nested While Loop
  • Python Infinite While Loop
  • Python Pattern Programs using While Loop
  • Python For Loop – Range
  • Python For Loop – Access Index
  • Python For Loop – Increment in Steps
  • Python Addition
  • Python Subtraction
  • Python Multiplication
  • Python Division
  • Python Modulus
  • Python Exponentiation
  • Python Floor Division
  • Python Assignment
  • Python Addition Assginment
  • Python Subtraction Assginment
  • Python Multiplication Assginment
  • Python Division Assginment
  • Python Modulus Assginment
  • Python Exponentiation Assignment
  • Python Floor Division Assignment
  • Python Equal
  • Python Not Equal
  • Python Greater than
  • Python Less than
  • Python Greater than or Equal to
  • Python Less than or Equal to
  • Python is not
  • Python Membership Operators
  • Python Bitwise Operators
  • Python Functions
  • Python - abs()
  • Python - all()
  • Python - any()
  • Python - ascii()
  • Python - bin()
  • Python - bool()
  • Python - breakpoint()
  • Python - bytearray()
  • Python - bytes()
  • Python - callable()
  • Python - chr()
  • Python - classmethod()
  • Python - compile()
  • Python - complex()
  • Python - delattr()
  • Python - dict()
  • Python - dir()
  • Python - divmod()
  • Python - enumerate()
  • Python - eval()
  • Python - exec()
  • Python - filter()
  • Python - float()
  • Python - format()
  • Python - frozenset()
  • Python - getattr()
  • Python - globals()
  • Python - hasattr()
  • Python - hash()
  • Python - help()
  • Python - hex()
  • Python - id()
  • Python - input()
  • Python - int()
  • Python - isinstance()
  • Python - issubclass()
  • Python - iter()
  • Python - len()
  • Python - list()
  • Python - locals()
  • Python - map()
  • Python - max()
  • Python - memoryview()
  • Python - min()
  • Python - next()
  • Python - object()
  • Python - oct()
  • Python - open()
  • Python - ord()
  • Python - pow()
  • Python - print()
  • Python - property()
  • Python - range()
  • Python - repr()
  • Python - reversed()
  • Python - round()
  • Python - set()
  • Python - setattr()
  • Python - slice()
  • Python - sorted()
  • Python - staticmethod()
  • Python - str()
  • Python - sum()
  • Python - super()
  • Python - tuple()
  • Python - type()
  • Python - vars()
  • Python - zip()
  • Python - import()
  • Python String capitalize()
  • Python String casefold()
  • Python String center()
  • Python String count()
  • Python String encode()
  • Python String endswith()
  • Python String expandtabs()
  • Python String find()
  • Python String format()
  • Python String format_map()
  • Python String index()
  • Python String isalnum()
  • Python String isalpha()
  • Python String isdecimal()
  • Python String isdigit()
  • Python String isidentifier()
  • Python String islower()
  • Python String isnumeric()
  • Python String isprintable()
  • Python String isspace()
  • Python String istitle()
  • Python String isupper()
  • Python String join()
  • Python String ljust()
  • Python String lower()
  • Python String lstrip()
  • Python String maketrans()
  • Python String partition()
  • Python String replace()
  • Python String rfind()
  • Python String rindex()
  • Python String rjust()
  • Python String rpartition()
  • Python String rsplit()
  • Python String rstrip()
  • Python String split()
  • Python String splitlines()
  • Python String startswith()
  • Python String strip()
  • Python String swapcase()
  • Python String title()
  • Python String translate()
  • Python String upper()
  • Python String zfill()
  • Python – Create empty string
  • Python – Create string using single quotes
  • Python – Create string using double quotes
  • Python – Check if string ends with a specific suffix
  • Python – Check if string starts with a specific prefix
  • Python – Count number of occurrences of a substring
  • Python – Find smallest string in a list based on length
  • Python – Find smallest of strings lexicographically in a list
  • Python – Get character at specific index from string
  • Python – Get first character from string
  • Python – Get last character from string
  • Python – Length of string
  • Python – Substring
  • Python – Convert string to a list of characters
  • Python – Escape single quote in a string
  • Python – Escape double quote in a string
  • Python – Iterate over characters of a string
  • Python – Print unique characters of a string
  • Python – Replace substring in string
  • Python – Sort list of strings
  • Python – Split string
  • Python – Trim string
  • Python – Write string to text file
  • Python List append()
  • Python List extend()
  • Python List insert()
  • Python List remove()
  • Python List pop()
  • Python List clear()
  • Python List index()
  • Python List count()
  • Python List sort()
  • Python List reverse()
  • Python List copy()
  • Get length of List
  • Iterate over Elements of List
  • Python List While Loop
  • Python List For Loop
  • Sorting a Python List
  • Pop last element from Python List
  • Delete specific element or item at given index from List
  • Convert Tuple into a List
  • Reverse a Python List
  • Python Dictionary clear()
  • Python Dictionary copy()
  • Python Dictionary get()
  • Python Dictionary items()
  • Python Dictionary keys()
  • Python Dictionary values()
  • Python Dictionary fromkeys()
  • Python Dictionary pop()
  • Python Dictionary popitem()
  • Python Dictionary setdefault()
  • Python Dictionary update()
  • Python Get keys of dictionary as list
  • Python Get values of dictionary as list
  • Python Get dictionary length
  • Python Tuple count()
  • Python Tuple index()
  • Python Create a tuple
  • Python Access items of tuple
  • Python Length of tuple
  • Python Iterete over items of tuple
  • Python Check if all items of tuple are true
  • Python Check if any of the items of tuple are true
  • Python Find maximum value in tuple
  • Python Find minimum value in tuple
  • Transformations
  • Python Reverse tuple
  • Python Sort tuple
  • Python Slice tuple
  • Python Filter tuple
  • Conversions
  • Python Convert tuple into list
  • Python Convert list of tuples to dictionary
  • Python set add()
  • Python set clear()
  • Python set copy()
  • Python set difference()
  • Python set difference_update()
  • Python set discard()
  • Python set intersection()
  • Python set intersection_update()
  • Python set isdisjoint()
  • Python set issubset()
  • Python set issuperset()
  • Python set pop()
  • Python set remove()
  • Python set symmetric_difference()
  • Python set symmetric_difference_update()
  • Python set union()
  • Python set update()
  • Python - Create a Set
  • Python - Set length
  • Python - Iterate over elements of Set
  • Python - set() builtin function
  • Python - Check if Set contains specific element
  • Python - Find largest number in Set
  • Python - Find smallest number in Set
  • Python - Find shortest string in Set
  • Python - Find longest string in Set
  • Python - Filter elements of Set
  • Numpy Tutorial
  • SciPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • ❯ Python Tutorial

Python Assignment Operator

Assignment operator.

Python Assignment Operator is used to assign a value to a variable. The value could be the result of evaluating an expression, return value from a function, or another variable, etc.

In this tutorial, we will learn the syntax of Assignment Operator and how to use it, with examples.

The syntax of Assignment Operator is

where variable_name is any Python Variable , and value is a string literal, a number , constant, value returned from a function call, an expression, etc.

= symbol is used for Assignment Operator.

Assign a Value to Variable

In the following program, we assign a value of 'hello world' to the variable message .

Python Interpreter assigns the value given on the right hand side to the variable in the left hand side.

Assign an Expression to a Variable

We can assign an expression to the variable using assignment operator.

In the following example, we have taken two variables: a , b with values 10, 25 assigned to them respectively. In the third statement, are assigning the expression a + b to the variable result .

In the following example, we assign a variable with different values one by one, and print them to console.

Python Program

In this Python Tutorial , we learned the syntax of Assignment Operator, and how to use it to assign a value to a variable.

Popular Courses by TutorialKart

App developement, web development, online tools.

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

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.

cropped-white-logo 1

  • Case Studies
  • Our Pricing
  • Do my Programming Homework
  • Java Homework Help
  • HTML Homework Help
  • Do my computer science homework
  • C++ Homework Help
  • C Homework Help
  • Python Assignment Help
  • Android Assignment help
  • Database Homework Help
  • PHP Assignment Help
  • JavaScript Assignment Help
  • R Assignment Help
  • Node.Js Homework Help
  • Data Structures Assignment Help
  • Machine Learning Assignment Help
  • MATLAB Assignment Help
  • C Sharp Assignment Help
  • Operating System Assignment Help
  • Assembly Language Assignment Help
  • Scala Assignment Help
  • Visual Basic Assignment Help
  • Live Java Tutoring
  • Python Tutoring
  • Our Experts
  • Testimonials
  • Submit Your Assignment

Understanding The Assignment Operators In Python

Assignment Operators in Python

While learning any Programming Language, the basics should be clear to you. This fits well with the Python programming language. The concept of Assignment Operators will be the best to start. That is why learning “Assignment Operators In Python” is necessary.

Among many other beginner concepts in Python Language, the Operators get more concentration because this will frame the future path in your career. So, if you are going to start learning Python, you should focus more on Python Assignment Operators.

This article will discuss the basics of Python Assignment Operators. Also, we will perform operations with Python Assignment Operators for clear understanding. So, let’s start this interesting journey.

If you encounter any challenges in grasping these operators, don’t hesitate to seek Python help from the experts at CodingZap.

Summary or Key Highlights:

Operator is a Mathematical Operations with two variables or Oparends & one Operator.

There are many Operators in Python like Assignment Operators, Bitwise Operators, Logical Operations, etc.

The key task of the Python Assignment Operators is to assign values to the variables.

To assign values with Python Assignment Operators, you need to know the relationship between Operators and Operands .

Python Assignment Operators can be created with other operators in Python.

What Are Assignment Operators In Python? Read Below

The operator is a simple Mathematical Expression where Two Operands & One Operator are used to make one complete expression. The Operator is placed in the middle & there are Left-Side Operand and Right-Side Operand.

In the expression “a+b”,  “+” is the operator, and “a” and “b” are the operands. Assignment operators are a fundamental concept in Python and most programming languages. They are used to assign values to variables, as well as initialize and update them.

For the Coding Language, sometimes the Right-Side Operand can be a value as well. The main role of the Basic Assignment Operator is to assign values to the Left Operand from the Right Operand. If the Left Operand is present as a variable, then only the complete process can be done.

How To Use Assignment Operator In Python?

Now, after the definition, we are coming to the technique to use Python Assignment Operators. That means here, we will discuss the syntax of the Python Assignment Operators. So for that purpose, check the following example.

From the above syntax, the Python Assignment Variable can be defined. You can notice that the Python Assignment Operator can be differentiated into three parts. Let us check those three parts here.

The left-side operand of an assignment statement must always and only be a variable. 

Then comes the assignment operator itself.

The right-side operand can be a value, an expression, or an object. 

What Are Different Assignment Operators In Python?

Now, it is time to move ahead to the central discussion point. Here, we will implement a Python Assignment Operator for each class. There are multiple types of Python Assignment Operators are present. And each of the cases, the Assigning Values will behave differently.

Before moving to Other assignment operators, let us start with the very simple one. This is known as the Simple Assignment Operator or Basic Assignment Operator.

Python Homework Help

1. Simple Assignment Operator or Basic Assignment Operator:

It is a very simple implementation process. Here, we will follow the Syntax declared above and implement the Python Code. We will just assign the value to the left to some new variables. It is also known as the Primary Assignment Operator.

Simple Assignment Operator

2. Multiple And Parallel Assignment Operator:

Now, the Multiple And Parallel Assignment is not mentioned as the categories of the Assignment Operator. However, we can still write them in the section. We can say that, they are the variations of the Simple Equal Operator.

Short Explanation For Multiple Assignments:

In the above code, the integer value 45 is assigned to all the variables a,b,c. The data type of all the variables in a multiple-assignment statement must be the same.

Short Explanation For Parallel Assignment:

In parallel assignments, we can assign different values to different variables using comma-separated variables and values on either side of the assignment operator. The values are stored in the order of writing the pairs. The variable types need not be the same in parallel assignments. 

Multiple And Parallel Assignment Operator

3. Addition Assignment Operator:

This operator adds the left and the right operands and assigns the resulting value to the variable on the left. An example would be a += b which will equate to a = a+b .

It is important to note that only the value of “a” will change, whereas the value of “b” will remain the same. This is because the sum of “a” and “b” is finally stored in the variable “a”.

Short Explanation:

In the above code, we initialized 2 variables and added the value of the second variable to the first one using the add assignment operator. Note that the value of “a” changes, but the value of “b” remains the same. 

Addition Assignment Operator

4. Subtraction Assignment Operator:

After Addition One, it is time to move to the Subtraction Operation . This operator subtracts the right operand from the left and assigns the resulting value to the variable on the left. The working process is nearly the same as the above one.

In the above code, we initialized the 2 variables “a” and “b” and printed their values for reference. Then, we subtracted the value of “b” from “a” using the subtract assignment operator. The final expression equated to “a=a-b”. At last, we printed the final values of “a” and “b”.

Subtraction Assignment Operator

5. Multiplication Assignment Operator:

Now, it is time to discuss the Multiplication Assignment Operation which is similar to the above one. The multiplication assignment operator is used to multiply the right operand with the left and assign the resulting value to the variable on the left. 

In the above code, we initialized the 2 variables “a” and “b” and printed their values for reference. Then, we multiplied the values of “a” and “b” using the multiplication equal operator. The final expression equated to “a=a*b”. At last, we printed the final values of “a” and “b” to check the resulting values. 

Multiplication Assignment Operator

6. Division Assignment Operator:

Just like the previous three operators, the Division Operator works the same. Just instead of other operators, we have to put the Disivion Symbol there.

The Division Assignment Operator divides the left-hand operand from the right and assigns the resulting value to the left-hand side.

In the above code, we initialized the 2 variables “a” and “b” and printed their values for reference. Then, we divided “a” by “b” using the division assignment operator. The final expression equated to “a=a/b”. At last, we printed the final values of “a” and “b”. 

Division Assignment Operator

7. Floor Division Assignment Operator:

Now, you have seen the Division Operator. Now, it is time to move to the Floor Division Operator. This is quite different from the simple division operator.

The floor division operator divides the operand on the left-hand operand from the right and rounds the value to the greatest integer value less than or equal to the resultant value. This value is then stored in the left-hand side operand.

In the above code, we initialized the 2 variables “a” and “b” and printed their values for reference. Then, we divided “a” by “b” using the division assignment operator. The final expression equated to “a=a//b”. At last, we printed the final values of “a” and “b”. 

Floor Division Assignment Operator

8. Modulus Assignment Operator:

In this case, the Modulus Assignment Operator is defined with the help of the Modulus and Equal Operator. That means the Simple Modulus and Assignment or Equal Operator will be used to get the Modulus value after dividing.

The modulus assignment operator is used to extract the remainder after dividing the operand on the left-hand side operand from the right. The remainder is then stored in the operand on the left-hand side operand.

In the above code, we initialized the 2 variables “a” and “b” and printed their values for reference. We then used the Modulus Equal Operator to get the remainder of the division “a/b”, and store the resulting value in “a”. At last, we printed the final values of “a” and “b”. 

Modulus Assignment Operator

9. Exponentiation Assignment Operator:

You might know the Power Operation in Mathematics! The same is present in Python Coding Language as well. This operator is used to get the Power of the Left Operand. This is the operator that can be used for various operations in the future.

This operator calculates the exponent of the left operand raised to the power of the right-side operand, which is then stored in the operand on the left.

In the above code, we initialized the 2 variables “a” and “b” and printed their values for reference. We then used the exponentiation assignment operator to get the value of “a” raised to the power of “b”, and store the resulting value in “a”. At last, we printed the final values of “a” and “b”. 

Exponentiation Assignment Operator

10. Bitwise And Assignment Operator:

You might have come across the And Operator where the Special Symbol “&” is used. It is mostly used in the Computer Organization subject. However, it can be used with the Equal Operator. This operator performs the And Operation in between Left Operand & Ride-Side Operand.

And it will assign the result to the left operand. That men’s, the Left Side is very important in this case as well.

In the above code, we initialized the 2 variables “a” and “b” and printed their values for reference. We then used the bitwise AND assignment operator to get the bitwise AND of “a” and “b”, and store the resulting value in “a”. At last, we printed the final values of “a” and “b”. 

Bitwise And Assignment Operator

What Are Common Pitfalls With Assignment Operators And How to Avoid Them?

Now, after all the above discussion, before we end the topic, we should share some of the challenges that you may face while working on the Assignment Operators. We are going to list all the problems that as a beginner, you might face. So, let us check the following points.

If there are mutable objects like List or Dictionary, then you should be careful to make sudden changes there as it might cause problems later.

You should not declare another variable in the Inner Scope of the program. If you done so, there will be an Error before executing the code.

If you are doing the changes in the Global Variable with Assignment Operators, then there can be consequences in the entire code. So, you have to be very careful.

However, we understand your situation. And we are not going to leave you by giving the list of pitfalls. We will help you to give Some Tips To Overcome such a problem. 

Tips that can be used to overcome such situations:

If you are using mutable objects, then the NONE should be used at the time of declaration to avoid the problem.

Always use a different name or name to depict the logic to overcome the situation to use the same name. You can use this trick for all languages.

If you are modifying the Global Variable inside the function, then use the keyword properly. Hence, there will not be any kind of issues.

Conclusion:

As we can see, it is very important to know the “Assignment Operators In Python”.

Operators are the fundamental part of any Coding Language that as a beginner you should have to practice. If the Python Operator Concept becomes clear to you, all the other problems can easily be solved.

There are many reasons why students look for assignment help online like difficulty in understanding the assignment, time limitation, etc. So, if you’re also looking then you can always hire CodinngZap experts.

Additionally, consider  hiring Python tutors  to accelerate your learning journey and gain personalized guidance along the way.

Assignment Operators assign the value to the Left Operand from the Right-Hand Side.

Assignment Operators assign the result to the left-hand side along with making all the changes.

Assignment Operators can be utilized with other Operators in Python as well.

As the Assignment Operators can assign the result after making prompt calculations, they can be divided into categories.

In each of the cases, before assigning value to the left, the Primary Operations like Addition, Multiplication, Substractions, etc. are done first, then the Assigning Operation.

Sounetra Ghosal

Sounetra Ghosal

Leave a comment cancel reply.

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

Our best Coding Help Services

  • Do my programming homework
  • Computer Science hw help
  • Database homework assistance
  • HTML coding help
  • Android Help
  • Java Assignment Help
  • C programming Help
  • Python Coding Help
  • Assembly Coding Help
  • Node.Js help
  • C Sharp help
  • Machine Learning task help
  • PHP project help
  • Operating System Help

CodingZap white Logo

CodingZap is founded back in 2015 with a mindset to provide genuine programming help to students across the globe. We cater to a broad range of programming homework help services to students and techies who are struggling with their code.

Programming Help Expertise

Contact us now.

  • HQ USA: 920 Beach Park Blvd, Foster City, USA
  • +1 (332) 895-6153
  • [email protected]

CodingZap accepts all major Debit and Credit cards payment.

Important Links

Copyright 2015-2024 CodingZap Technologies Private Limited- All rights reserved.

  • +919035109861

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

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 - Home
  • Python - Introduction
  • Python - Syntax
  • Python - Comments
  • Python - Variables
  • Python - Data Types
  • Python - Numbers
  • Python - Type Casting
  • Python - Operators
  • Python - Booleans
  • Python - Strings
  • Python - Lists
  • Python - Tuples
  • Python - Sets
  • Python - Dictionary
  • Python - If Else
  • Python - While Loop
  • Python - For Loop
  • Python - Continue Statement
  • Python - Break Statement
  • Python - Functions
  • Python - Lambda Function
  • Python - Scope of Variables
  • Python - Modules
  • Python - Date & Time
  • Python - Iterators
  • Python - JSON
  • Python - File Handling
  • Python - Try Except
  • Python - Arrays
  • Python - Classes/Objects
  • Python - Inheritance
  • Python - Decorators
  • Python - RegEx
  • Python - Operator Overloading
  • Python - Built-in Functions
  • Python - Keywords
  • Python - String Methods
  • Python - File Handling Methods
  • Python - List Methods
  • Python - Tuple Methods
  • Python - Set Methods
  • Python - Dictionary Methods
  • Python - Math Module
  • Python - cMath Module
  • Python - Data Structures
  • Python - Examples
  • Python - Q&A
  • Python - Interview Questions
  • Python - NumPy
  • Python - Pandas
  • Python - Matplotlib
  • Python - SciPy
  • Python - Seaborn

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Python - assignment operators example

The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • **= Exponent AND assignment operator
  • %= Modulo AND assignment operator
  • //= Floor division AND assignment operator

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

assignment operator about list in Python

I am a beginner in Python, I cannot understand assignment operator clearly, for example:

the above two statements bind 'list1' and 'list2' to ["Tom", "Sam", "Jim"] , the question is, if a operator like below:

list1[1] = "Sam's sister" , if the assignment statement is considered as binding, too, then list2[1] is still associated with "Sam", the result is that modifying list1 does not affect the list2 , even though Python presents the opposite output, another question is whether list1[1] can be regarded as a variable as list1 and list2 in Python.

can anyone have any suggestions?

Michael Berkowski's user avatar

  • Yes, list1[1] can be treated as a variable, but make sure that the list actually has at least two elements. Otherwise Python will complain that the index 1 couldn't be accessed. –  Maria Ines Parnisari Commented Oct 15, 2012 at 2:27
  • Related: How to clone or copy a list? –  Aran-Fey Commented Sep 21, 2018 at 9:40

4 Answers 4

In your example the identifiers list1 and list2 are references to the same underlying object ( just different names for the same thing ).

id() can be used to see if the same underlying object is being referenced.

To create a copy of the defined list use the [:] notation, or deepcopy as Matthew has mentioned. You'll notice that when this is done the location/id has changed.

About the id command:

monkut's user avatar

You're right, they aren't the same. Assignment to a bare name in Python ( name = ... ) is a different operation than assignment to anything else. In particular it is different from item assignment ( name[0] = ... ) and attribute assignment ( name.attr = ... ). They all use the equal sign, but the latter two are manipulable with hooks ( __setitem__ and __setattr__ ), can call arbitrary code, and are generally under the control of the programmer. Assignment to a bare name is not under the control of the Python programmer. You can't affect what it does; it always just binds the right hand side to the name on the left hand side.

This can be confusing, because people are used to thinking that the equals sign is what makes an "assignment". But in Python, in order to understand what operation is taking place, you really have to look on the left of the equals sign and see what kind of thing is being assigned to.

BrenBarn's user avatar

BrenBarn is absolutely right about everything, but here is another way to look at it that might be easier to understand:

Your first statement creates a list with those values, then makes list1 point to it. The second statement makes list2 point to exactly the same memory space as list1. (You can see this by running id on both of them after the second statement).

At that point list1 and list2 are essentially both references to the same mutable list. When you change that list, list1 and list2 are still both referencing the same actual list and using either to access it will give you the same thing.

I did a blog post about a related topic recently and Python Conquers the Universe also talks about a similar topic here .

TimothyAWiseman's user avatar

BrenBam has a good explanation of what is going on. deepcopy a way to get around it:

Good programming style will make it rare to have to actually use deepcopy though.

Matthew Adams's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python or ask your own question .

  • Featured on Meta
  • Announcing a change to the data-dump process
  • We've made changes to our Terms of Service & Privacy Policy - July 2024

Hot Network Questions

  • Any idea what game this picture is from?
  • The difference between ii°7 and vii°7
  • What kind of navy could island nations with populations in the few 100k range build to fight eachother in a 1890s-1920s century naval technology?
  • How will a very short undergrad impact PhD applications?
  • In practice, what are the identities in the Needham–Schroeder protocol?
  • Commentaries relevant to doubled phrases in Aleinu
  • Could Swashplate be replaced with small electric motors?
  • How to make a command completely null
  • Why isn’t this formula used at all?
  • Is another interview required for SENTRI/Trusted Traveler renewal
  • How to make an operator form of Part[] to use with // (Postfix)
  • What is the best way to close this small gap in the tile?
  • Is a Fizban's dragonborn's breath weapon magical?
  • How can I safely cut cultured countertops containing silica?
  • RP2040 ADC calibration (schematic)
  • Automata reaching the same state when reading the same word long enough
  • Accessing an overridden Greek letter
  • How can I handle unavailable papers in a systematic literature review?
  • Jurisdiction: Can police officers open mail addressed to a stranger?
  • Two vectors can be expressed in a basis where both have all nonzero entries
  • How is the name "Took" pronounced?
  • How to fix my PC after an accidental reboot during upgrade to ubuntu 24.04?
  • Does GDPR's "Legitimate Interest" allow spam?
  • DC motor pump always transports in same direction, regardless of polarity

assignment operator python example

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

JavaScript ( JS ) is a lightweight interpreted (or just-in-time compiled) programming language with first-class functions . While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js , Apache CouchDB and Adobe Acrobat . JavaScript is a prototype-based , multi-paradigm, single-threaded , dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

JavaScript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval ), object introspection (via for...in and Object utilities ), and source-code recovery (JavaScript functions store their source text and can be retrieved through toString() ).

This section is dedicated to the JavaScript language itself, and not the parts that are specific to Web pages or other host environments. For information about APIs that are specific to Web pages, please see Web APIs and DOM .

The standards for JavaScript are the ECMAScript Language Specification (ECMA-262) and the ECMAScript Internationalization API specification (ECMA-402). As soon as one browser implements a feature, we try to document it. This means that cases where some proposals for new ECMAScript features have already been implemented in browsers, documentation and examples in MDN articles may use some of those new features. Most of the time, this happens between the stages 3 and 4, and is usually before the spec is officially published.

Do not confuse JavaScript with the Java programming language — JavaScript is not "Interpreted Java" . Both "Java" and "JavaScript" are trademarks or registered trademarks of Oracle in the U.S. and other countries. However, the two programming languages have very different syntax, semantics, and use.

JavaScript documentation of core language features (pure ECMAScript , for the most part) includes the following:

  • The JavaScript guide
  • The JavaScript reference

For more information about JavaScript specifications and related technologies, see JavaScript technologies overview .

Learn how to program in JavaScript with guides and tutorials.

For complete beginners

Head over to our Learning Area JavaScript topic if you want to learn JavaScript but have no previous experience with JavaScript or programming. The complete modules available there are as follows:

Answers some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", along with discussing key JavaScript features such as variables, strings, numbers, and arrays.

Continues our coverage of JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.

The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you.

Discusses asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.

Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work.

JavaScript guide

A much more detailed guide to the JavaScript language, aimed at those with previous programming experience either in JavaScript or another language.

Intermediate

JavaScript frameworks are an essential part of modern front-end web development, providing developers with proven tools for building scalable, interactive web applications. This module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to a series of tutorials covering some of today's most popular ones.

An overview of the basic syntax and semantics of JavaScript for those coming from other programming languages to get up to speed.

Overview of available data structures in JavaScript.

JavaScript provides three different value comparison operations: strict equality using === , loose equality using == , and the Object.is() method.

How different methods that visit a group of object properties one-by-one handle the enumerability and ownership of properties.

A closure is the combination of a function and the lexical environment within which that function was declared.

Explanation of the widely misunderstood and underestimated prototype-based inheritance.

Memory life cycle and garbage collection in JavaScript.

JavaScript has a runtime model based on an "event loop".

Browse the complete JavaScript reference documentation.

Get to know standard built-in objects Array , Boolean , Date , Error , Function , JSON , Math , Number , Object , RegExp , String , Map , Set , WeakMap , WeakSet , and others.

Learn more about the behavior of JavaScript's operators instanceof , typeof , new , this , the operator precedence , and more.

Learn how do-while , for-in , for-of , try-catch , let , var , const , if-else , switch , and more JavaScript statements and keywords work.

Learn how to work with JavaScript's functions to develop your applications.

JavaScript classes are the most appropriate way to do object-oriented programming.

New Transformation `..` Operator to Transform Values

Hello Everyone,

I am proposing new transformation operator syntax that can be used in various ways including creating ranges, type conversion, and applying functions:

We can also use another forms of this operator for extended functionalities including ( <.. , >.. , ^.. ) or ( ... or .... , ..... , ...... ) to be used as exclusive types of transformations.

There can particular focus on .. operator for the proposal, and the other operator can be divided into a different topic or proposal as an extension if needed.

If there is a need to seperate the range and pipe functionality, we can use the operator :: or ::: for ranges while .. for pipe functionality.

I do like Ruby’s range capabilities like 'a'..'zz' and Date.today..(Date.today + 7) and myClassInstance..anotherInstance , but those other usages you showed just look odd/bad. Why would you want to write those instead of the normal way?

Thank you for your reply. I think of this operator as a general operator that can have various applications including ranges by just overriding its method __transformation__ and thus allowing different ways for using this operator. Of course this issue can be discussed further and changed as required by development team. It’s just an idea that can be explored further and discussed more.

An idea is FAR more compelling if it starts with a real, concrete use-case, not just “hey, what would happen if we did this?”. Syntax is a big deal. We don’t have syntax for every random little thing that might be convenient. Even when something would have significant value for a subset of Python users, it can take a long time and a lot of debating to get it added (see PEP 465 for one that eventually succeeded).

So, what’s the use-case here? If it’s nothing more than the start of a discussion, this can be moved to Python Help instead.

Thank you for your reply. It can be used as a new syntax that simplifies some coding operations as specified in the examples in the proposal. The proposal is flexible and open for changes as it’s discussed. There is value in this proposal that could add new features for the language, however, the implementation of this proposal is decided by development team and community if seen as a good addition to the language.

This topic is 2 different ideas in 1 big proposal with extensive syntax changes.

It does not answer or cover issues and questions raised in previous discussions about these matters.

a) Function application does not seem to offer anything new. It currently looks like calling the function by writing things in different order. b) Range Literals: PEP 204 - Range Literals: Getting closure .

Given the size of suggested changes in comparison to accompanying research and analysis, I am moving this to “Help”. It could be useful to discuss these and brainstorm further for those who are interested to join in at this stage.

If OP is willing to make a longer commitment to working on these, I would suggest tackling each a) and b) separately.

So this is np.linspace function, but less flexible. Step is 1 out of 3 main components in range/sequence construction and is not mentioned anywhere.

If the intent of function application is to provide composition (which is not shown in examples), then more realistic proposal would be to add functools.pipe . This in combination with functools.partial would cover the functionality without introduction of new syntax.

There is also c) Matrix algebra operators.

Currently, tensor objects re-use __add__ , __sub__ , __mul__ . While these operations with list vectors are easily done with list(map(operator.add, A, B)))

@dg-pb Yes, the first case of ranges for float/double values needs more research and discussion. The initial idea is to infer the step from the size of the decimal places of the given number so for 1.0, it’s 0.1 step, which wouldn’t work for 1.00 for 0.01 step value or 1.0 for 0.2 step value. Suggestion:

The concepts in the proposal are very related and It’s possible to divide the proposal into sub proposals as required by the development team and community. Thank you

Figure out what your proposal is. Don’t hide behind vagueness. At the moment, there isn’t enough concrete content here to even discuss; you’ve thrown out this broad set of ideas and you’re hoping that other people will do the work required to turn it into something useful.

@Rosuav The proposal is clear it’s just open for more discussion as needed. What’s not clear for you so it can be clarified better. The proposal is about a new list of transformation operators starting with .. with the .. being general and then the other variations( +.. , >.. ) are specific. They can be used for type conversion, and creating ranges and also pipe functions.

To me they seem related only by the operator syntax. Apart from that to me they all look completely different judged on applications, implementations and implications.

If you dive into them properly by committing to these for longer time, you will see how many different underlying issues, questions and obstacles each of them has.

In other words, this looks like 1% baked idea. Although such posts are not desirable in “Ideas” section, I would not mind discussing it in “Help” section if these were posted separately.

Currently, the scope is just too wide and ideas are too raw. You need to do a bit of cooking and/or a bit of narrowing for this to be productive discussion.

But what do they DO ? What is the point of them? You’re proposing a new syntax without showing any particular purpose to it - you’ve shown a range syntax (but we’ve already had that proposed and rejected, and you haven’t explained how your proposal is better), and a super generic “this could do anything” concept. There is no purpose to it. There is no coherency. What is your actual proposal?

I mentioned them in the main proposal post.

1>..10 is used for generating numbers from 2 to 10 if step is 1 value. []+..[] is used for adding matrices.

I’m suggesting to move these extra extension operators to a different proposal as needed, while the focus for the current proposal is .. operator functionality.

IMO, this needs to be convenient and flexible. I.e. step size would be very much preferable to create range objects.

This creation of range/sequence objects is very verbose and would not be convenient at all.

Open/closed is not as important from flexibility POV as one can always just have different starting/ending values. For simplicity and consistency, it might be best just to keep things in line with slice / range closed bound to open bound.

The best that I can think of at the moment is introduction of ternary operator. I am not sure about syntax/naming/etc, but it could look like:

For int, it would produce ranges, and it could be a good place to start.

Regarding other classes, it should be carefully evaluated what sort of functionality would bring most value. For list, it could be matrix algebra. E.g.:

But I doubt that this would/should end up in standard library. If the user needs this, it would be possible to implement it easily.

If you want to start by focusing on ranges , I would strongly suggest having a thorough read of PEP 204 - Range Literals: Getting closure - #32 by jbo .

Also, one more question. Are you suggesting this for someone else to do or is it something that you desire to work on yourself?

I don’t see where the transformation is happening… When I read ‘transformation operator,’ I was thinking of something like this: Transformation Operator .

Also, please take a look at Python Discuss FAQ .

It’s a general transformation not mathematical transformation. For example "1"..int transform string to int value.

it’s an idea that I think it could be a good addition for the language and it’s open for discussion. I’m can certainly help in the implementation as needed.

What I don’t really get.

then why doesn’t

(or TypeError: 'int' object is not callable )

The operator checks for the types for operands given if the second operand is a function then it calls that function with the first operand. if the they are numbers, it creates a range list. if any operand is a tuple, it checks the tuple type and size (as used in the main post) and then creates a range list.

  • 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

How to Fix “Could Not Identify an Equality Operator for Type Python JSON”?

When working with JSON data in programming languages like JavaScript or TypeScript we might encounter an error message stating “Could Not Identify an Equality Operator for Type JSON.” This error occurs because the JSON objects are not natively comparable using equality operators like == or === in many programming languages.

Problem Statement

Consider a scenario where we have JSON objects and we want to compare them for equality in the code. However, when attempting to do so the error:

ds00

This error typically arises because JSON objects are not directly comparable using the standard equality operators due to their structure and properties.

Understanding the Issue

PostgreSQL provides two data types for storing JSON data: json and jsonb . The json data type stores an exact copy of the input text, which preserves whitespace, order of keys, and duplicates. However, it does not support indexing and lacks an equality operator. On the other hand, jsonb datatype stores JSON data in a decomposed binary format, supports indexing, and provides operators for equality comparison.

Scenarios Causing the Error

  • Using json Type in a Unique Constraint or Primary Key : PostgreSQL cannot enforce uniqueness without an equality operator, leading to errors.
  • Using json Data Type in JOIN Clauses : Without an equality operator, it’s impossible to perform JOIN operations on columns of type json .

Solutions to Fix the “Could Not Identify an Equality Operator for Type Python JSON” Error

Here are several approaches to resolve this error, focusing on transitioning to the jsonb data type or redefining how data is used and stored.

1. Convert json Columns to jsonb

The most straightforward solution to this problem is converting existing json columns to jsonb . The jsonb data type supports all operations that require an equality operator.

SQL Command to Alter Column Type

This command converts a column from json to jsonb safely, ensuring all current functionalities remain intact while gaining new capabilities.

2. Use JSON Data Wisely in Schemas

If converting to jsonb is not feasible, reconsider how JSON data is used within your database schema:

  • Avoid using JSON for Primary Keys : Store essential identifiers in separate, type-appropriate columns.
  • Avoid JSON in JOIN Clauses : Extract key information into separate columns that can be indexed and joined efficiently.

3. Query Adjustment in Python

When working with PostgreSQL and JSON data in Python, particularly using libraries like psycopg2 , adjust your queries to cast json to jsonb where necessary, or ensure all operations on JSON columns do not require an equality comparison.

Example Python Code

4. data normalization.

Consider normalizing data where possible:

  • Extract keys : If you frequently access specific keys within JSON, consider extracting these into separate columns.
  • Table transformations : Transform JSON fields into multiple columns or even separate tables, depending on the complexity and usage of the data.

5. Custom Equality Function

Implement a function that compares two JSON objects for the equality. This function will recursively traverse the objects and compare each key-value pair.

6. Using a Library (Lodash)

If we prefer using a library, Lodash provides a utility function _.isEqual() that can compare two JSON objects deeply.

Code Example

Let’s illustrate how the problem is resolved with the code example:

Setup PostgreSQL Table with jsonb

You can set this up directly in your PostgreSQL client or use a script:

Step 2: Python Script to Interact with PostgreSQL

This script will connect to the PostgreSQL database, insert a new jsonb record, and then perform a query to retrieve records where the JSON data matches certain criteria.

By utilizing jsonb and the associated operators, you can perform complex queries on JSON data stored in PostgreSQL, overcoming limitations that arise with the json data type.

By implementing a custom equality check function or using the library like Lodash we can effectively compare JSON objects for the equality in the applications resolving the “Could Not Identify an Equality Operator for Type JSON” error. This approach ensures robust handling of the JSON data comparisons in the code.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Python Tutorials: Assignment Operators In python

    assignment operator python example

  2. Python Operators

    assignment operator python example

  3. Assignment operators in python

    assignment operator python example

  4. Assignment Operators in Python

    assignment operator python example

  5. Python Operators

    assignment operator python example

  6. Python Operators

    assignment operator python example

VIDEO

  1. Assignment

  2. Python Assignment Operator #coding #assignmentoperators #phython

  3. Assignment operator #operator #operator in python #python #code #datascience #pythonfullcourse

  4. Become a Python Expert: Secrets and Guide of Assignment Operator

  5. python assignment operator

  6. Python Tip! Assignment operator in Python #python #programming #basic #shorts #django #coding

COMMENTS

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

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

  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. The Walrus Operator: Python 3.8 Assignment Expressions

    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.

  5. Python Assignment Operators

    print(num) Run. 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)

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

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

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

  9. Python Assignment Operators

    Here is an example of using the assignment operator to assign a value to a variable: x = 5 In this example, the variable x is assigned the value 5. There are also several compound assignment operators in Python, which are used to perform an operation and assign the result to a variable in a single step. These operators include: +=: adds the ...

  10. Assignment Operators in Python

    There are three types of assignment operators in Python: 1. Simple Python Assignment Operator (=) This assigns the value on the right-hand side (RHS) to the variable on the left-hand side (LHS). You can use a literal, another variable, or an expression in the assignment statement.

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

  12. Python Assignment Operators

    Assignment operators are used to assign values to variables. note. There are various compound operators in Python. For example, a += 2 adds 2 to the variable and then assigns it to the variable. It is equivalent to a = a + 2. Operator Description Example Equivalent to =

  13. Python Assignment Operator

    In this tutorial, we will learn the syntax of Assignment Operator and how to use it, with examples. Syntax. The syntax of Assignment Operator is. variable_name = value. where variable_name is any Python Variable, and value is a string literal, a number, constant, value returned from a function call, an expression, etc. = symbol is used for ...

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

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

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

  17. Assignment Operators in Python

    Now that we have this rule clear let us look at the assignment operators in Python. The assignment operators allow us to create, initialise and update the variables. The simple assignment operator "=" It is the primary assignment operator. Let's look at some examples to understand the uses of the simple assignment operator:

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

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

  20. python

    Since Python 3.8, code can use the so-called "walrus" operator (:=), documented in PEP 572, for assignment expressions.This seems like a really substantial new feature, since it allows this form of assignment within comprehensions and lambdas.. What exactly are the syntax, semantics, and grammar specifications of assignment expressions?

  21. Python Assignment Operator: A Comprehensive Guide 2024!

    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.

  22. Python assignment operators example

    The example below shows the usage of assignment and compound assignment operators: = Assignment operator. += Addition AND assignment operator. -= Subtraction AND assignment operator. *= Multiply AND assignment operator. /= Division AND assignment operator. **= Exponent AND assignment operator. %= Modulo AND assignment operator.

  23. assignment operator about list in Python

    You're right, they aren't the same. Assignment to a bare name in Python (name = ...) is a different operation than assignment to anything else. In particular it is different from item assignment (name[0] = ...) and attribute assignment (name.attr = ...They all use the equal sign, but the latter two are manipulable with hooks (__setitem__ and __setattr__), can call arbitrary code, and are ...

  24. JavaScript

    JavaScript (JS) is a lightweight interpreted (or just-in-time compiled) programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented ...

  25. New Transformation `..` Operator to Transform Values

    Hello Everyone, I am proposing new transformation operator syntax that can be used in various ways including creating ranges, type conversion, and applying functions: a = (1..10) # list of numbers from 1 to 10 inclusive a = (0.0..1.0) # list of numbers from 0 to 1 by 0.1 inclusive. ((1,0.02)..2) #list of numbers from 1 to 2 by 0.02 by using tuple value (1..(2,0.02)) #list of numbers from 1 to ...

  26. How to Fix "Could Not Identify an Equality Operator for Type Python

    When working with PostgreSQL and JSON data in Python, particularly using libraries like psycopg2, adjust your queries to cast json to jsonb where necessary, or ensure all operations on JSON columns do not require an equality comparison. Example Python Code Python