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 Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

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

Python Object & Class

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

Python Operator Overloading

Python Advanced Topics

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

Python Date and Time

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

Additional Topic

Precedence and Associativity of Operators in Python

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

Python Tutorials

Python 3 Tutorial

  • Python Strings
  • Python any()

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

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

  • Types of Python Operators

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

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

1. Python Arithmetic Operators

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

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

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

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 in python meaning

previous episode

Python for absolute beginners, next episode, variables and assignment.

Overview Teaching: 15 min Exercises: 15 min Questions How can I store data in programs? Objectives Write scripts that assign values to variables and perform calculations with those values. Correctly trace value changes in scripts that use assignment.

Use variables to store values

Variables are one of the fundamental building blocks of Python. A variable is like a tiny container where you store values and data, such as filenames, words, numbers, collections of words and numbers, and more.

The variable name will point to a value that you “assign” it. You might think about variable assignment like putting a value “into” the variable, as if the variable is a little box 🎁

(In fact, a variable is not a container as such but more like an adress label that points to a container with a given value. This difference will become relevant once we start talking about lists and mutable data types.)

You assign variables with an equals sign ( = ). In Python, a single equals sign = is the “assignment operator.” (A double equals sign == is the “real” equals sign.)

  • Variables are names for values.
  • In Python the = symbol assigns the value on the right to the name on the left.
  • The variable is created when a value is assigned to it.
  • Here, Python assigns an age to a variable age and a name in quotation marks to a variable first_name :

Variable names

Variable names can be as long or as short as you want, but there are certain rules you must follow.

  • Cannot start with a digit.
  • Cannot contain spaces, quotation marks, or other punctuation.
  • May contain an underscore (typically used to separate words in long variable names).
  • Having an underscore at the beginning of a variable name like _alistairs_real_age has a special meaning. So we won’t do that until we understand the convention.
  • The standard naming convention for variable names in Python is the so-called “snake case”, where each word is separated by an underscore. For example my_first_variable . You can read more about naming conventions in Python here .

Use meaningful variable names

Python doesn’t care what you call variables as long as they obey the rules (alphanumeric characters and the underscore). As you start to code, you will almost certainly be tempted to use extremely short variables names like f . Your fingers will get tired. Your coffee will wear off. You will see other people using variables like f . You’ll promise yourself that you’ll definitely remember what f means. But you probably won’t.

So, resist the temptation of bad variable names! Clear and precisely-named variables will:

  • Make your code more readable (both to yourself and others).
  • Reinforce your understanding of Python and what’s happening in the code.
  • Clarify and strengthen your thinking.

Use meaningful variable names to help other people understand what the program does. The most important “other person” is your future self!

Python is case-sensitive

Python thinks that upper- and lower-case letters are different, so Name and name are different variables. There are conventions for using upper-case letters at the start of variable names so we will use lower-case letters for now.

Off-Limits Names

The only variable names that are off-limits are names that are reserved by, or built into, the Python programming language itself — such as print , True , and list . Some of these you can overwrite into variable names (not ideal!), but Jupyter Lab (and many other environments and editors) will catch this by colour coding your variable. If your would-be variable is colour-coded green, rethink your name choice. This is not something to worry too much about. You can get the object back by resetting your kernel.

Use print() to display values

We can check to see what’s “inside” variables by running a cell with the variable’s name. This is one of the handiest features of a Jupyter notebook. Outside the Jupyter environment, you would need to use the print() function to display the variable.

You can run the print() function inside the Jupyter environment, too. This is sometimes useful because Jupyter will only display the last variable in a cell, while print() can display multiple variables. Additionally, Jupyter will display text with \n characters (which means “new line”), while print() will display the text appropriately formatted with new lines.

  • Python has a built-in function called print() that prints things as text.
  • Provide values to the function (i.e., the things to print) in parentheses.
  • To add a string to the printout, wrap the string in single or double quotations.
  • The values passed to the function are called ‘arguments’ and are separated by commas.
  • When using the print() function, we can also separate with a ‘+’ sign. However, when using ‘+’ we have to add spaces in between manually.
  • print() automatically puts a single space between items to separate them.
  • And wraps around to a new line at the end.

Variables must be created before they are used

If a variable doesn’t exist yet, or if the name has been misspelled, Python reports an error (unlike some languages, which “guess” a default value).

The last line of an error message is usually the most informative. This message lets us know that there is no variable called eye_color in the script.

Variables Persist Between Cells Variables defined in one cell exist in all other cells once executed, so the relative location of cells in the notebook do not matter (i.e., cells lower down can still affect those above). Notice the number in the square brackets [ ] to the left of the cell. These numbers indicate the order, in which the cells have been executed. Cells with lower numbers will affect cells with higher numbers as Python runs the cells chronologically. As a best practice, we recommend you keep your notebook in chronological order so that it is easier for the human eye to read and make sense of, as well as to avoid any errors if you close and reopen your project, and then rerun what you have done. Remember: Notebook cells are just a way to organize a program! As far as Python is concerned, all of the source code is one long set of instructions.

Variables can be used in calculations

  • We can use variables in calculations just as if they were values. Remember, we assigned 42 to age a few lines ago.

This code works in the following way. We are reassigning the value of the variable age by taking its previous value (42) and adding 3, thus getting our new value of 45.

Use an index to get a single character from a string

  • The characters (individual letters, numbers, and so on) in a string are ordered. For example, the string ‘AB’ is not the same as ‘BA’. Because of this ordering, we can treat the string as a list of characters.
  • Each position in the string (first, second, etc.) is given a number. This number is called an index or sometimes a subscript.
  • Indices are numbered from 0 rather than 1.
  • Use the position’s index in square brackets to get the character at that position.

Use a slice to get a substring

A part of a string is called a substring. A substring can be as short as a single character. A slice is a part of a string (or, more generally, any list-like thing). We take a slice by using [start:stop] , where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want. Mathematically, you might say that a slice selects [start:stop] . The difference between stop and start is the slice’s length. Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string.

Use the built-in function len() to find the length of a string

The built-in function len() is used to find the length of a string (and later, of other data types, too).

Note that the result is 6 and not 7. This is because it is the length of the value of the variable (i.e. 'helium' ) that is being counted and not the name of the variable (i.e. element )

Also note that nested functions are evaluated from the inside out, just like in mathematics. Thus, Python first reads the len() function, then the print() function.

Choosing a Name Which is a better variable name, m , min , or minutes ? Why? Hint: think about which code you would rather inherit from someone who is leaving the library: ts = m * 60 + s tot_sec = min * 60 + sec total_seconds = minutes * 60 + seconds Solution minutes is better because min might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).
Swapping Values Draw a table showing the values of the variables in this program after each statement is executed. In simple terms, what do the last three lines of this program do? x = 1.0 y = 3.0 swap = x x = y y = swap Solution swap = x # x->1.0 y->3.0 swap->1.0 x = y # x->3.0 y->3.0 swap->1.0 y = swap # x->3.0 y->1.0 swap->1.0 These three lines exchange the values in x and y using the swap variable for temporary storage. This is a fairly common programming idiom.
Predicting Values What is the final value of position in the program below? (Try to predict the value without running the program, then check your prediction.) initial = "left" position = initial initial = "right" Solution initial = "left" # Initial is assigned the string "left" position = initial # Position is assigned the variable initial, currently "left" initial = "right" # Initial is assigned the string "right" print(position) left The last assignment to position was “left”
Can you slice integers? If you assign a = 123 , what happens if you try to get the second digit of a ? Solution Numbers are not stored in the written representation, so they can’t be treated like strings. a = 123 print(a[1]) TypeError: 'int' object is not subscriptable
Slicing What does the following program print? library_name = 'social sciences' print('library_name[1:3] is:', library_name[1:3]) If thing is a variable name, low is a low number, and high is a high number: What does thing[low:high] do? What does thing[low:] (without a value after the colon) do? What does thing[:high] (without a value before the colon) do? What does thing[:] (just a colon) do? What does thing[number:negative-number] do? Solution library_name[1:3] is: oc It will slice the string, starting at the low index and ending an element before the high index It will slice the string, starting at the low index and stopping at the end of the string It will slice the string, starting at the beginning on the string, and ending an element before the high index It will print the entire string It will slice the string, starting the number index, and ending a distance of the absolute value of negative-number elements from the end of the string
Key Points Use variables to store values. Use meaningful variable names. Python is case-sensitive. Use print() to display values. Variables must be created before they are used. Variables persist between cells. Variables can be used in calculations. Use an index to get a single character from a string. Use a slice to get a substring. Use the built-in function len to find the length of a string.

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 in python meaning

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.

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

Python Assignment Operator

  • Introduction

Chained Assignment

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

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

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

Different Assignment Methods

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

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

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

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

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

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

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

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

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

Operator Meaning
+= Add the value on the right to the variable on the left
-= Subtract the value on the right from the variable on the left
*= Multiply with the variable on the right, and add to the result on the left
/= Divide by the variable on the right, and add to the result on the left

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

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

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

Summary: Python Assignment Operator

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

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 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 »
  • 3.12.4 Documentation »
  • The Python Language Reference »
  • 7. Simple statements
  • Theme Auto Light Dark |

7. Simple statements ¶

A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is:

7.1. Expression statements ¶

Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None ). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is:

An expression statement evaluates the expression list (which may be a single expression).

In interactive mode, if the value is not None , it is converted to a string using the built-in repr() function and the resulting string is written to standard output on a line by itself (except if the result is None , so that procedure calls do not cause any output.)

7.2. Assignment statements ¶

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

(See section Primaries for the syntax definitions for attributeref , subscription , and slicing .)

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy ).

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty).

Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Assignment of an object to a single target is recursively defined as follows.

If the target is an identifier (name):

If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.

Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal , respectively.

The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.

If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, TypeError is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError ).

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The left-hand side target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment:

This description does not necessarily apply to descriptor attributes, such as properties created with property() .

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If the primary is a mutable sequence object (such as a list), the subscript must yield an integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).

If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/value pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

For user-defined objects, the __setitem__() method is called with appropriate arguments.

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it.

CPython implementation detail: In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2] :

The specification for the *target feature.

7.2.1. Augmented assignment statements ¶

Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement:

(See section Primaries for the syntax definitions of the last three symbols.)

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place , meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i] , then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i] .

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.

For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments.

7.2.2. Annotated assignment statements ¶

Annotation assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement:

The difference from normal Assignment statements is that only a single target is allowed.

The assignment target is considered “simple” if it consists of a single name that is not enclosed in parentheses. For simple assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute __annotations__ that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically.

If the assignment target is not simple (an attribute, subscript node, or parenthesized name), the annotation is evaluated if in class or module scope, but not stored.

If a name is annotated in a function scope, then this name is local for that scope. Annotations are never evaluated and stored in function scopes.

If the right hand side is present, an annotated assignment performs the actual assignment before evaluating annotations (where applicable). If the right hand side is not present for an expression target, then the interpreter evaluates the target except for the last __setitem__() or __setattr__() call.

The proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments.

The proposal that added the typing module to provide a standard syntax for type annotations that can be used in static analysis tools and IDEs.

Changed in version 3.8: Now annotated assignments allow the same expressions in the right hand side as regular assignments. Previously, some expressions (like un-parenthesized tuple expressions) caused a syntax error.

7.3. The assert statement ¶

Assert statements are a convenient way to insert debugging assertions into a program:

The simple form, assert expression , is equivalent to

The extended form, assert expression1, expression2 , is equivalent to

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O ). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

7.4. The pass statement ¶

pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

7.5. The del statement ¶

Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.

Deletion of a target list recursively deletes each target, from left to right.

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).

Changed in version 3.2: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block.

7.6. The return statement ¶

return may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None ) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. A non-empty return statement is a syntax error in an asynchronous generator function.

7.7. The yield statement ¶

A yield statement is semantically equivalent to a yield expression . The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements

are equivalent to the yield expression statements

Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

For full details of yield semantics, refer to the Yield expressions section.

7.8. The raise statement ¶

If no expressions are present, raise re-raises the exception that is currently being handled, which is also known as the active exception . If there isn’t currently an active exception, a RuntimeError exception is raised indicating that this is an error.

Otherwise, raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException . If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

The type of the exception is the exception instance’s class, the value is the instance itself.

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute. You can create an exception and set your own traceback in one step using the with_traceback() exception method (which returns the same exception instance, with its traceback set to its argument), like so:

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance. If the second expression is an exception instance, it will be attached to the raised exception as the __cause__ attribute (which is writable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the __cause__ attribute. If the raised exception is not handled, both exceptions will be printed:

A similar mechanism works implicitly if a new exception is raised when an exception is already being handled. An exception may be handled when an except or finally clause, or a with statement, is used. The previous exception is then attached as the new exception’s __context__ attribute:

Exception chaining can be explicitly suppressed by specifying None in the from clause:

Additional information on exceptions can be found in section Exceptions , and information about handling exceptions is in section The try statement .

Changed in version 3.3: None is now permitted as Y in raise X from Y .

Added the __suppress_context__ attribute to suppress automatic display of the exception context.

Changed in version 3.11: If the traceback of the active exception is modified in an except clause, a subsequent raise statement re-raises the exception with the modified traceback. Previously, the exception was re-raised with the traceback it had when it was caught.

7.9. The break statement ¶

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

If a for loop is terminated by break , the loop control target keeps its current value.

When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

7.10. The continue statement ¶

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.

7.11. The import statement ¶

The basic import statement (no from clause) is executed in two steps:

find a module, loading and initializing it if necessary

define a name or names in the local namespace for the scope where the import statement occurs.

When the statement contains multiple clauses (separated by commas) the two steps are carried out separately for each clause, just as though the clauses had been separated out into individual import statements.

The details of the first step, finding and loading modules, are described in greater detail in the section on the import system , which also describes the various types of packages and modules that can be imported, as well as all the hooks that can be used to customize the import system. Note that failures in this step may indicate either that the module could not be located, or that an error occurred while initializing the module, which includes execution of the module’s code.

If the requested module is retrieved successfully, it will be made available in the local namespace in one of three ways:

If the module name is followed by as , then the name following as is bound directly to the imported module.

If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module

If the module being imported is not a top level module, then the name of the top level package that contains the module is bound in the local namespace as a reference to the top level package. The imported module must be accessed using its full qualified name rather than directly

The from form uses a slightly more complex process:

find the module specified in the from clause, loading and initializing it if necessary;

for each of the identifiers specified in the import clauses:

check if the imported module has an attribute by that name

if not, attempt to import a submodule with that name and then check the imported module again for that attribute

if the attribute is not found, ImportError is raised.

otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

If the list of identifiers is replaced by a star ( '*' ), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__ ; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ( '_' ). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

The wild card form of import — from module import * — is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError .

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod . If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod . The specification for relative imports is contained in the Package Relative Imports section.

importlib.import_module() is provided to support applications that determine dynamically the modules to be loaded.

Raises an auditing event import with arguments module , filename , sys.path , sys.meta_path , sys.path_hooks .

7.11.1. Future statements ¶

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard.

The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.

A future statement must appear near the top of the module. The only lines that can appear before a future statement are:

the module docstring (if any),

blank lines, and

other future statements.

The only feature that requires using the future statement is annotations (see PEP 563 ).

All historical features enabled by the future statement are still recognized by Python 3. The list includes absolute_import , division , generators , generator_stop , unicode_literals , print_function , nested_scopes and with_statement . They are all redundant because they are always enabled, and only kept for backwards compatibility.

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it.

The direct runtime semantics are the same as for any import statement: there is a standard module __future__ , described later, and it will be imported in the usual way at the time the future statement is executed.

The interesting runtime semantics depend on the specific feature enabled by the future statement.

Note that there is nothing special about the statement:

That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions.

Code compiled by calls to the built-in functions exec() and compile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to compile() — see the documentation of that function for details.

A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.

The original proposal for the __future__ mechanism.

7.12. The global statement ¶

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global , although free variables may refer to globals without being declared global.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.

CPython implementation detail: The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.

Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. The same applies to the eval() and compile() functions.

7.13. The nonlocal statement ¶

When the definition of a function or class is nested (enclosed) within the definitions of other functions, its nonlocal scopes are the local scopes of the enclosing functions. The nonlocal statement causes the listed identifiers to refer to names previously bound in nonlocal scopes. It allows encapsulated code to rebind such nonlocal identifiers. If a name is bound in more than one nonlocal scope, the nearest binding is used. If a name is not bound in any nonlocal scope, or if there is no nonlocal scope, a SyntaxError is raised.

The nonlocal statement applies to the entire scope of a function or class body. A SyntaxError is raised if a variable is used or assigned to prior to its nonlocal declaration in the scope.

The specification for the nonlocal statement.

Programmer’s note: nonlocal is a directive to the parser and applies only to code parsed along with it. See the note for the global statement.

7.14. The type statement ¶

The type statement declares a type alias, which is an instance of typing.TypeAliasType .

For example, the following statement creates a type alias:

This code is roughly equivalent to:

annotation-def indicates an annotation scope , which behaves mostly like a function, but with several small differences.

The value of the type alias is evaluated in the annotation scope. It is not evaluated when the type alias is created, but only when the value is accessed through the type alias’s __value__ attribute (see Lazy evaluation ). This allows the type alias to refer to names that are not yet defined.

Type aliases may be made generic by adding a type parameter list after the name. See Generic type aliases for more.

type is a soft keyword .

Added in version 3.12.

Introduced the type statement and syntax for generic classes and functions.

Table of Contents

  • 7.1. Expression statements
  • 7.2.1. Augmented assignment statements
  • 7.2.2. Annotated assignment statements
  • 7.3. The assert statement
  • 7.4. The pass statement
  • 7.5. The del statement
  • 7.6. The return statement
  • 7.7. The yield statement
  • 7.8. The raise statement
  • 7.9. The break statement
  • 7.10. The continue statement
  • 7.11.1. Future statements
  • 7.12. The global statement
  • 7.13. The nonlocal statement
  • 7.14. The type statement

Previous topic

6. Expressions

8. Compound statements

  • Report a Bug
  • Show Source
  • School Guide
  • Class 11 Syllabus
  • Class 11 Revision Notes
  • Maths Notes Class 11
  • Physics Notes Class 11
  • Chemistry Notes Class 11
  • Biology Notes Class 11
  • NCERT Solutions Class 11 Maths
  • RD Sharma Solutions Class 11
  • Math Formulas Class 11

Augmented Assignment Operators in Python

An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write “ a = 5 “ to assign value 5 to variable ‘a’. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator. So assume if we need to add 7 to a variable “a” and assign the result back to “a”, then instead of writing normally as “ a = a + 7 “, we can use the augmented assignment operator and write the expression as “ a += 7 “. Here += has combined the functionality of arithmetic addition and assignment.

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

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

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

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

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

Example:  

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Please Login to comment...

Similar reads.

  • School Learning
  • School Programming

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Table of Contents

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

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.

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.

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 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 in python meaning

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
  • Module 2: The Essentials of Python »
  • Variables & Assignment
  • View page source

Variables & Assignment 

There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.

Variables permit us to write code that is flexible and amendable to repurpose. Suppose we want to write code that logs a student’s grade on an exam. The logic behind this process should not depend on whether we are logging Brian’s score of 92% versus Ashley’s score of 94%. As such, we can utilize variables, say name and grade , to serve as placeholders for this information. In this subsection, we will demonstrate how to define variables in Python.

In Python, the = symbol represents the “assignment” operator. The variable goes to the left of = , and the object that is being assigned to the variable goes to the right:

Attempting to reverse the assignment order (e.g. 92 = name ) will result in a syntax error. When a variable is assigned an object (like a number or a string), it is common to say that the variable is a reference to that object. For example, the variable name references the string "Brian" . This means that, once a variable is assigned an object, it can be used elsewhere in your code as a reference to (or placeholder for) that object:

Valid Names for Variables 

A variable name may consist of alphanumeric characters ( a-z , A-Z , 0-9 ) and the underscore symbol ( _ ); a valid name cannot begin with a numerical value.

var : valid

_var2 : valid

ApplePie_Yum_Yum : valid

2cool : invalid (begins with a numerical character)

I.am.the.best : invalid (contains . )

They also cannot conflict with character sequences that are reserved by the Python language. As such, the following cannot be used as variable names:

for , while , break , pass , continue

in , is , not

if , else , elif

def , class , return , yield , raises

import , from , as , with

try , except , finally

There are other unicode characters that are permitted as valid characters in a Python variable name, but it is not worthwhile to delve into those details here.

Mutable and Immutable Objects 

The mutability of an object refers to its ability to have its state changed. A mutable object can have its state changed, whereas an immutable object cannot. For instance, a list is an example of a mutable object. Once formed, we are able to update the contents of a list - replacing, adding to, and removing its elements.

To spell out what is transpiring here, we:

Create (initialize) a list with the state [1, 2, 3] .

Assign this list to the variable x ; x is now a reference to that list.

Using our referencing variable, x , update element-0 of the list to store the integer -4 .

This does not create a new list object, rather it mutates our original list. This is why printing x in the console displays [-4, 2, 3] and not [1, 2, 3] .

A tuple is an example of an immutable object. Once formed, there is no mechanism by which one can change of the state of a tuple; and any code that appears to be updating a tuple is in fact creating an entirely new tuple.

Mutable & Immutable Types of Objects 

The following are some common immutable and mutable objects in Python. These will be important to have in mind as we start to work with dictionaries and sets.

Some immutable objects

numbers (integers, floating-point numbers, complex numbers)

“frozen”-sets

Some mutable objects

dictionaries

NumPy arrays

Referencing a Mutable Object with Multiple Variables 

It is possible to assign variables to other, existing variables. Doing so will cause the variables to reference the same object:

What this entails is that these common variables will reference the same instance of the list. Meaning that if the list changes, all of the variables referencing that list will reflect this change:

We can see that list2 is still assigned to reference the same, updated list as list1 :

In general, assigning a variable b to a variable a will cause the variables to reference the same object in the system’s memory, and assigning c to a or b will simply have a third variable reference this same object. Then any change (a.k.a mutation ) of the object will be reflected in all of the variables that reference it ( a , b , and c ).

Of course, assigning two variables to identical but distinct lists means that a change to one list will not affect the other:

Reading Comprehension: Does slicing a list produce a reference to that list?

Suppose x is assigned a list, and that y is assigned a “slice” of x . Do x and y reference the same list? That is, if you update part of the subsequence common to x and y , does that change show up in both of them? Write some simple code to investigate this.

Reading Comprehension: Understanding References

Based on our discussion of mutable and immutable objects, predict what the value of y will be in the following circumstance:

Reading Comprehension Exercise Solutions: 

Does slicing a list produce a reference to that list?: Solution

Based on the following behavior, we can conclude that slicing a list does not produce a reference to the original list. Rather, slicing a list produces a copy of the appropriate subsequence of the list:

Understanding References: Solutions

Integers are immutable, thus x must reference an entirely new object ( 9 ), and y still references 3 .

Currently Reading :

Currently reading:

Simple assignment operator in Python

Different assignment operators in python.

Rajat Gupta

Software Developer

Published on  Thu Jun 30 2022

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

Assignment Operators in Python

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

  • Bitwise and operator

Bitwise OR operator

  • Bitwise XOR Assignment operator

Bitwise right shift assignment operator

Bitwise left shift assignment operator.

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

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

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

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

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

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

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

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

Bitwise And operator

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

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

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

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

Bitwise XOR operator

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

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

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

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

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

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

Closing Thoughts

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

About the author

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

Related Blogs

4 Ways to implement Python Switch Case Statement

Sanchitee Ladole

Converting String to Float in Python

Ancil Eric D'Silva

Memoization Using Decorators In Python

Harsh Pandey

Harsh Pandey

Python Increment - Everything you need to know

Theano Python Beginner Guide for Getting Started

Taygun Dogan

Taygun Dogan

17 min read

Python Classes And Objects

Browse Flexiple's talent pool

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

  • Programmers
  • React Native
  • Ruby on Rails

What is Assignment Operator in Python?

Assignment Operators thumbnail

Before deep-diving into the assignment operators in Python, first, understand what operators are. So operators are used in between the operands to perform various operations, like mathematical operations , bitwise operations , logical operations , and so on. Here, operands are the values on which operators perform the actions. So, assignment operators are used to assigning values to the operands on the left-hand side. Assignment operators assign the right-hand side values to the operand that is present on the left-hand side. The assignment operator in Python is used as the "=" symbol.

Let’s see a very basic example of the assignment operator.

Table Of Assignment Operators

Here we will see different assignment operators in Python with their names, descriptions, and syntax. Let's take them one by one.

OperatorNameDescriptionSyntax
Assignment OperatorIt assigns the right-hand side expression value to the operand present on the left-hand side.a=b+c
Addition Assignment OperatorThis operator adds left and right operands, and after that, it assigns the calculated value to the left-hand operand.a+=b or a=a+b
Subtraction Assignment OperatorThis operator subtracts the right operand from the left operand and assigns the result to the left operand.a-=b or a=a-b
Multiplication Assignment OperatorThis operator will multiply the left-hand side operand by the right-hand side operand and, after that, assign the result to the left-hand operand.a*=b or a=a*b
Division Assignment OperatorThis operator will divide the left-hand side operand by the right-hand side operand and, after that, assign the result to the left-hand operand.a/=b or a=a/b
Modulus Assignment OperatorThis operator will divide the left-hand side operand by the right-hand side operand and, after that, assign the reminder to the left-hand operand.a%=b or a=a%b
Exponentiation Assignment OperatorThis operator raises the left-side operand to the power of the right-side operand and assigns the result to the left-side value.a**=b or a=a**b
Floor Division Assignment OperatorThis operator will divide the left operand by the right operand and assign the quotient value (which would be in the form of an integer) to the left operand.a//=b or a=a//b
Bitwise AND Assignment OperatorThis operator will perform the bitwise operation on both the left and right operands and, after that, it will assign the resultant value to the left operand.a&=b or a=a&b
Bitwise OR Assignment OperatorThis operator will perform the bitwise or operation on both the left and right operands and, after that, it will assign the resultant value to the left operand.a|=b or a=a|b
Bitwise XOR Assignment OperatorThis operator will perform the bitwise XOR operation on the left and right operands and, after that, it will assign the resultant value to the left operand.a^=b or a=a^b
Bitwise Right Shift Assignment OperatorThis operator will right-shift the left operand by the specified position, i.e., b, and after that, it will assign the resultant value to the left operand.a>>=b or a=a>>b
Bitwise Left Shift Assignment OperatorThis operator will left shift the left operand by the specified position, i.e., b, and after that, it will assign the resultant value to the left operand.a<<=b or a=a<<b

Assignment Operator :

This is an assignment operator in Python which assigns the right-hand side expression value to the operand present on the left-hand side.

Sample Code :

Addition Assignment Operator :

This type of assignment operator in Python adds left and right operands, and after that, it assigns the calculated value to the left-hand operand.

Subtraction Assignment Operator :

This operator subtracts the right operand from the left operand and assigns the result to the left operand.

Multiplication Assignment Operator:

This operator will multiply the left-hand side operand by the right-hand side operand and, after that, assign the result to the left-hand operand.

Division Assignment Operator :

This type of assignment operator in Python will divide the left-hand side operand from the right-hand side operand and, after that, assign the result to the left-hand operand.

Modulus Assignment Operator :

This operator will divide the left-hand side operand to the right-hand side operand and, after that, assign the reminder to the left-hand operand.

Click here, to learn more about modulus in python .

Exponentiation Assignment Operator :

This operator raises the left-side operand to the power of the right-side operand and assigns the result to the left-side value.

Floor Division Assignment Operator :

This operator will divide the left operand by the right operand and assign the quotient value (which would be in the form of an integer) to the left operand.

Bitwise AND Assignment Operator :

This operator will perform the bitwise operation on both the left and right operands and, after that, it will assign the resultant value to the left operand.

Bitwise OR Assignment Operator:

This operator will perform the bitwise or operation on both the left and right operands and, after that, it will assign the resultant value to the left operand.

Bitwise XOR Assignment Operator:

This operator will perform the bitwise XOR operation on the left and right operands and, after that, it will assign the resultant value to the left operand.

Bitwise Right Shift Assignment Operator :

This operator will right shift the left operand by the specified position, i.e., b , and after that, it will assign the resultant value to the left operand.

Bitwise Left Shift Assignment Operator:

This operator will left shift the left operand by the specified position, i.e., b , and after that, it will assign the resultant value to the left operand.

  • Assignment operators in Python assign the right-hand side values to the operand that is present on the left-hand side.
  • The assignment operators in Python is used as the "=" symbol.
  • We have different types of assignment operators like +=, -=, \*=, %=, /=, //=, \*\*=, &=, |=, ^=, >>=, <<= .
  • All the operators have the same precedence, and hence we prioritise operations based on their associativiy . The associativity is from right to left.

Learn More:

  • XOR in Python .

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.

Javatpoint Logo

Python Tutorial

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

JavaTpoint

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

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

Following are the examples of the assignment operators:

Following are the different types of assignment operators in Python:

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

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

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

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

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

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

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

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

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

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

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

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

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





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • HTML Assignment Experts
  • PHP Assignment Experts
  • CSS Assignment Experts
  • JavaScript Assignment Experts
  • Experienced Data Structures Assignment Experts | Low-cost Rates
  • Computer Networking Assignment Experts
  • Assembly Language Assignment Doers – Great Discounts & Offers
  • Proficient Arduino Assignment Experts Reviewed By 3.5K Students
  • LISP Assignment Experts
  • OpenCV Assignment Experts
  • UML Assignment Experts
  • OpenGL Assignment Experts
  • Database Assignment Help

How to Approach Solving Programming Assignments in Python

Alex Taylor

Programming assignments, especially those involving mathematical computations and data manipulations, often appear daunting at first glance. The complexity of these tasks can lead to uncertainty and hesitation, particularly when students encounter new concepts or methods. However, with a structured approach and systematic breakdown of the problem, tackling such Python assignments becomes not only manageable but also rewarding. This blog aims to provide you with a clear framework for approaching programming assignments in Python, focusing on a practical example. Specifically, we will explore the process of reading a list of numbers, performing calculations to find their sum, mean, and standard deviation, and finally presenting these results effectively. This guide will offer the necessary steps and insights to successfully complete your task.

In the realm of programming, breaking down tasks into smaller, more manageable components is a fundamental strategy for success. Each component serves as a building block that contributes to the overall solution. By understanding the problem statement and identifying the key operations required—such as input handling, computation, and output formatting—you can systematically address the assignment's requirements. This approach not only simplifies the task but also enhances your understanding of how different programming concepts integrate to solve real-world problems.

Approaching Python Programming Assignments

The example assignment provided involves fundamental statistical computations: sum, mean, and standard deviation. These operations are foundational in both programming and data analysis contexts. Learning to execute these calculations programmatically not only sharpens your coding skills but also equips you with valuable tools for future assignments and projects. Python, with its clear syntax and extensive libraries like math for mathematical operations, proves to be an excellent choice for such tasks, enabling concise and efficient implementation of complex algorithms.

Throughout this guide, we will delve into each step of the solution, emphasizing clarity and correctness in coding practices. Understanding how to handle user input, compute mathematical formulas, and present results accurately are essential skills for any programmer. By mastering these techniques, you not only enhance your proficiency in Python programming but also build a strong foundation for tackling a wide range of programming challenges.

By the end of this blog, you will have gained practical insights into solving programming assignments, laying a solid groundwork for future learning and application. Whether you're a beginner seeking to understand the basics or an experienced programmer aiming to refine your skills, this guide aims to empower you with the tools and strategies needed to excel in solving similar programming tasks effectively. Let's embark on this journey to demystify programming assignments and empower your problem-solving capabilities in Python.

Understanding the Problem Statement

The first step in tackling any programming assignment is to thoroughly understand the problem statement. Read the instructions carefully and identify the key tasks required. For instance, in the given example, the assignment requires you to:

  • Read a list of numbers from the user.
  • Compute the sum of these numbers.
  • Calculate the mean (average) of the numbers.
  • Determine the standard deviation of the numbers.
  • Display the computed sum, mean, and standard deviation.

Understanding these requirements helps in planning the solution effectively.

Breaking Down the Task

Once you understand the problem, the next step is to break it down into smaller, manageable tasks. This modular approach not only simplifies the problem but also makes your code more organized and easier to debug. Here, we can divide the assignment into the following functions:

  • read_data(): This function will handle user input and store the numbers in a list.
  • compute_sum(list_of_numbers): This function will compute the sum of the numbers in the list.
  • compute_mean(list_of_numbers): This function will calculate the mean of the numbers.
  • compute_sd(list_of_numbers): This function will compute the standard deviation of the numbers.
  • display_result(sum, mean, sd): This function will print the sum, mean, and standard deviation.

Writing the Functions

Let’s dive into writing each function step by step.

Reading Data

The read_data() function is responsible for reading numbers from the user until an empty string is entered. These numbers are then stored in a list.

In this function, we use a while loop to continuously prompt the user for input. If the user enters an empty string, the loop breaks, indicating the end of input. We also include error handling to ensure that only valid integers are added to the list.

Computing the Sum

Next, the compute_sum(list_of_numbers) function calculates the sum of the numbers in the list.

Python's built-in sum() function makes this task straightforward and efficient.

Computing the Mean

The compute_mean(list_of_numbers) function calculates the mean by dividing the sum of the numbers by the length of the list.

Here, we reuse the compute_sum() function to get the sum of the numbers, ensuring that our code is modular and reusable.

Computing the Standard Deviation

The compute_sd(list_of_numbers) function calculates the standard deviation, which is a measure of the amount of variation or dispersion in a set of values.

This function calculates the variance by summing the squared differences between each number and the mean, then dividing by the number of observations minus one. The standard deviation is the square root of the variance.

Displaying the Results

Finally, the display_result(sum, mean, sd) function prints the computed sum, mean, and standard deviation in a formatted manner.

Using formatted strings (f-strings) ensures that the results are displayed with two decimal places, making them easy to read.

Integrating the Functions

With all the functions defined, the final step is to integrate them into a main program. The main() function coordinates the execution of all the individual functions.

In this main function, we call read_data() to get the list of numbers, then sequentially compute the sum, mean, and standard deviation, and finally display the results.

Debugging and Testing

A crucial part of solving programming assignments is debugging and testing your code. Here are some tips to help you debug and test effectively:

  • Test Incrementally: Test each function individually before integrating them. This helps isolate any errors and makes debugging easier.
  • Use Print Statements: Add print statements to check the values of variables at different stages of your program. This can help you understand the flow of data and identify where things might be going wrong.
  • Edge Cases: Consider edge cases, such as an empty list, a list with a single number, or very large numbers. Ensure your program handles these cases gracefully.
  • Code Review: If possible, have someone else review your code. A fresh set of eyes can often spot mistakes that you might have overlooked.

Error Handling and User Input Validation

Robust programs include error handling to manage unexpected inputs or situations. In our read_data() function, we included a try-except block to handle invalid inputs. Here’s a more detailed example:

This approach ensures that the user is prompted to enter valid numbers, enhancing the robustness of the program.

Documentation and Code Comments

Good documentation and code comments are essential for making your code understandable to others and to your future self. Use docstrings to describe the purpose and parameters of each function. Inline comments can explain complex or non-obvious parts of the code.

For example:

Enhancing and Extending the Program

Once you have a working solution, consider ways to enhance or extend the program. For example, you might add functionality to:

  • Save Results to a File: Allow users to save the results to a text file for future reference.
  • Plot Data: Use libraries like Matplotlib to create visualizations of the data and computed statistics.
  • Handle More Statistical Measures: Extend the program to compute other statistical measures, such as the median or mode.
  • Graphical User Interface (GUI): Create a GUI using Tkinter or another framework to make the program more user-friendly.

Practice and Continuous Learning

Programming is a skill that improves with practice. Continuously challenge yourself with new assignments and projects to build your problem-solving abilities and coding skills. Explore online resources, coding communities, and tutorials to learn new techniques and best practices.

In conclusion, successfully navigating Python programming assignments requires a methodical approach to problem-solving. Breaking down tasks into manageable components, writing clear and modular code, and diligently testing and debugging are essential steps in crafting robust solutions. By adhering to these principles, you can confidently tackle assignments that involve tasks such as data input handling, mathematical computations like sum and mean calculations, and the calculation of standard deviation. It's crucial to prioritize thorough documentation of your code to ensure clarity for both you and others who may review or use your work. Additionally, embracing a mind-set of continuous learning and improvement is key to advancing your skills as a programmer. Regular practice and exposure to diverse programming challenges will sharpen your abilities and pave the way towards becoming a proficient programmer.

In summary, approaching Python programming assignments effectively hinges on a structured methodology and attention to detail. By following the steps outlined in this blog, you will be well-equipped to tackle a variety of programming tasks with confidence and precision. Remember, each assignment is an opportunity to refine your coding skills and deepen your understanding of Python's capabilities. Embrace challenges as learning opportunities, and always strive for clarity, correctness, and efficiency in your code. With persistence and dedication, you'll build a strong foundation for success in your programming journey.

Post a comment...

  • 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 in python

I know that "variable assignment" in python is in fact a binding / re-bindign of a name (the variable) to an object.

This brings the question: is it possible to have proper assignment in python, eg make an object equal to another object?

I guess there is no need for that in python:

Inmutable objects cannot be 'assigned to' since they can't be changed

Mutable objects could potentially be assigned to, since they can change, and this could be useful, since you may want to manipulate a copy of dictionary separately from the original one. However, in these cases the python philosophy is to offer a cloning method on the mutable object, so you can bind a copy rather than the original.

So I guess the answer is that there is no assignment in python, the best way to mimic it would be binding to a cloned object

I simply wanted to share the question in case I'm missing something important here

Both Lie Ryan and Sven Marnach answers are good, I guess the overall answer is a mix of both:

For user defined types, use the idiom:

a. dict = dict(b. dict )

(I guess this has problems as well if the assigned class has redefined attribute access methods, but lets not be fussy :))

For mutable built-ins (lists and dicts) use the cloning / copying methods they provide (eg slices, update)

finally inmutable built-ins can't be changed so can't be assigned

I'll choose Lie Ryan because it's an elegant idiom that I hadn't thought of.

xuloChavez's user avatar

  • Are you asking about a deep copy? Is that what you mean by "binding to a cloned object"? –  S.Lott Commented Nov 17, 2010 at 11:58

3 Answers 3

I think you are right with your characterization of assignment in Python -- I just would like to add a different method of cloning and ways of assignment in special cases.

"Copy-constructing" a mutable built-in Python object will yield a (shallow) copy of that object:

[ Edit : As pointed out by Paul McGuire in the comments, the behaviour of a "copy contructor" (forgive me the C++ terminology) for a immutable built-in Python object is implementation dependent -- you might get a copy or just the same object. But because the object is immutable anyway, you shouldn't care.]

The copy constructor could be called generically by y = type(x)(x) , but this seems a bit cryptic. And of course, there is the copy module which allows for shallow and deep copies.

Some Python objects allow assignment. For example, you can assign to a list without creating a new object:

For dictionaries, you could use the clear() method followed by update(otherdict) to assign to a dictionary without creating a new object. For a set s , you can use

Sven Marnach's user avatar

  • Your "copy constructor" assumptions may hold true for the built-in Python classes, but they are not generally guaranteed for all classes and objects. I can very easily create an immutable class that takes an instance of itself for construction, but makes an entirely different object with the same values, such that copy == original is True, but copy is original is False. –  PaulMcG Commented Nov 17, 2010 at 13:11
  • I just noticed that you already qualified your answer to restrict it to the built-in classes. –  PaulMcG Commented Nov 17, 2010 at 13:12
  • A brief experiment with Jython 2.5.0 shows that this does not hold true for strings. : >>> a = "SLJDFSDLJ" >>> b = str(a) >>> b is a False - what you have described is an implementation optimization specific to CPython, but not guaranteed by the Python language spec. –  PaulMcG Commented Nov 17, 2010 at 13:15
  • For your own classes, you can always add some kind of assign() method if you need it -- that's why I focussed on the built-in types. –  Sven Marnach Commented Nov 17, 2010 at 13:16
  • @Paul McGuire: I'm surprised! I just tested with Python 2.6.6 and I get True ... To be honest, I'm really not sure any more the behaviour I described is guaranteed. I will investigate... –  Sven Marnach Commented Nov 17, 2010 at 13:19

Yes you can:

will do the default assignment semantic in C/C++ (i.e. do a shallow assignment).

The problem with such generalized assignment is that it never works for everybody. In C++, you can override the assignment operator since you always have to pick whether you want a fully shallow assignment, fully deep assignment, or any shade between fully deep copy and fully shallow copy.

Lie Ryan's user avatar

I don't think you are missing anything.

I like to picture variables in python as the name written on 'labels' that are attached to boxes but can change its placement by assignment, whereas in other languages, assignment changes the box's contents (and the assignment operator can be overloaded).

Beginners can write quite complex applications without being aware of that, but they are usually messy programs.

Marco Mariani'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
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Intersection in toric variety
  • Does the Ogre-Faced Spider regenerate part of its eyes daily?
  • Is it possible to complete a Phd on your own?
  • Do S&P 500 funds run by different investment companies have different performance based on the buying / selling speed of the company?
  • Viewport Shader Render different from 1 computer to another
  • Was Paul's Washing in Acts 9:18 a Ritual Purification Rather Than a Christian Baptism?
  • Are ordinary or qualified dividends taxed first?
  • Should I accept an offer of being a teacher assistant without pay?
  • Does this double well potential contradict the fact that there is no degeneracy for one-dimensional bound states?
  • Are there examples of triple entendres in English?
  • Do Christians believe that Jews and Muslims go to hell?
  • Con permiso to enter your own house?
  • How can a landlord receive rent in cash using western union
  • Artinian Gorenstein subrings with same socle degree
  • Summation of arithmetic series
  • Embedded terminal for Nautilus >= version 43
  • Remove assignment of [super] key from showing "activities" in Ubuntu 22.04
  • Examples of distribution for which first-order condition is not enough for MLE
  • Can you arrange 25 whole numbers (not necessarily all different) so that the sum of any three successive terms is even but the sum of all 25 is odd?
  • Why can't LaTeX (seem to?) Support Arbitrary Text Sizes?
  • What was the first game to intentionally use letterboxing to indicate a cutscene?
  • What is the term for when a hyperlink maliciously opens different URL from URL displayed when hovered over?
  • Is it better to show fake sympathy to maintain a good atmosphere?
  • In equation (3) from lecture 7 in Leonard Susskind’s ‘Classical Mechanics’, should the derivatives be partial?

assignment in python meaning

Disturbing behavior of assignment expressions in comprehensions

It took me some time to understand this strange behavior:

I think these weird results are a combination of two factors:

  • the assignment expression’s variable j is not visible in the if-clause and thus a global variable is used,
  • the assignment expression leaks the assigned variable into the global namespace.

As a result, the value of j used in the if-clause is not the one from the current iteration, but rather that from the previous iteration.

I find this behavior very misleading, and would call it a bug rather than a (bad) feature. My questions:

  • is my observation correct,
  • do other people also consider this behavior unwanted,
  • what can/should be done to fix it: propagate the assigned values through the whole comprehension, or avoid the leak into the global namespace, or both (my preference).

You have the evaluation order wrong.

In this example:

if the condition is false, the expression for the item is not evaluated.

It’s roughtly equivalent to this:

What you are looking for is:

I’m not looking for a way to solve this. I never use assignment expressions in comprehensions anyway. But look at the last two statements which are exactly the same, but they yield a different result. And if you change the name of the variable j, you get again something else. This looks like a flaky design to me, and certainly very confusing. While most of Python does precisely what you think it does, that is certainly not the case here.

I do find it surprising that the assignment expression leaks out of a comprehension (I only learned that in a recent discussion). It’s been known about for several years so I guess it isn’t considered a bug? Or maybe there’s some reason to allow it.

Wrong. It does do precisely what I think it does. I even hid the results from my view and tried to predict them, got all of them correct without any trouble.

There are a few notable exceptions to the usual rule of “evaluate left to right”, and if you don’t comprehend them (pun intended), you’ll be very confused. Some are fairly obvious to anyone who’s done any sort of programming work (eg the body of a function isn’t executed at the time of definition, it waits till it’s called), but others are less obvious. Keep in mind this evaluation order:

With that in mind, everything else makes sense. It’s only if you expect to first evaluate the result expression and only afterwards the condition that it’ll be confusing; and while that might seem logical, it also wouldn’t work the way every other guard does - imagine [1/x for x in range(-5, 5)] and then add a guard against division by zero [1/x for x in range(-5, 5) if x] which clearly has to be checked prior to the 1/x part.

I think you’re overblowing the problem here a bit. Calling something “disturbing” might be appropriate if you’re calling out someone’s lack of faith, but this is simply a fact to be learned. Calling the design “flaky” is definitely inaccurate - this is entirely reliable and dependable, it just wasn’t what you came in expecting. Treat it as a discovery moment, welcome it, and move on.

Yes, you’re right. I should have called it ‘surprising’ rather than ‘disturbing’. And it was surprising to me, obviously not to others. I would have liked that the variables assigned in the comprehension would have a local scope. But it is like it is, and changing that would be a breaking change. So it is something to just learn and remember how it works, and I’ve just done that. I’ve even become confident now to start using assignment expressions in comprehensions. Thanks all for the explanations.

The behavior of assignment expressions in comprehensions and generator expressions is intentional. Read PEP 572: Scope of the target .

Thanks for the link

Looks like a quiz or interview question.

While it seems a little surprising to a naive or tired brain, the first line actually gives it away.

If the first comprehension were replaced with an explicit j = 6 , the behaviour is not surprising at all.

In other words: it’s not about Python comprehension semantics, rather about this particular arrangement of code.

Related Topics

Topic Replies Views Activity
Ideas 6 1582 October 27, 2020
Python Help 3 369 June 5, 2023
Python Help 8 3486 September 9, 2022
Python Help 6 1411 January 8, 2020
Python Help 2 601 May 11, 2022

IMAGES

  1. PPT

    assignment in python meaning

  2. What are Python Assignment Expressions and Using the Walrus Operator

    assignment in python meaning

  3. Assignment Operators in Python

    assignment in python meaning

  4. What is Multiple Assignment in Python and How to use it?

    assignment in python meaning

  5. Assignment Operators in Python

    assignment in python meaning

  6. Assignment Operator in Python

    assignment in python meaning

VIDEO

  1. Assignment

  2. Variables and Multiple Assignment

  3. Assignment

  4. Python Assignment Operator #coding #assignmentoperators #phython

  5. 3#Assignment Operators in Python #pythonprogramming #computerlanguage

  6. Assignment

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  2. Python Assignment Operators

    Getting Started Mean Median Mode Standard Deviation Percentile Data Distribution Normal Data Distribution Scatter Plot Linear Regression Polynomial Regression Multiple Regression Scale Train/Test Decision Tree Confusion Matrix Hierarchical Clustering Logistic Regression ... Python Assignment Operators. Assignment operators are used to assign ...

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

  4. Different Forms of Assignment Statements in Python

    Multiple- target assignment: x = y = 75. print(x, y) In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left. OUTPUT. 75 75. 7. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment.

  5. Python Operators (With Examples)

    Here's a list of different assignment operators available in Python. Operator Name Example = Assignment Operator: a = 7 += Addition Assignment: a += 1 # a = a + 1 ... It's important to note that having two variables with equal values doesn't necessarily mean they are identical. Operator Meaning Example; is: True if the operands are identical ...

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

  7. Variables and Assignment

    In Python, a single equals sign = is the "assignment operator." (A double equals sign == is the "real" equals sign.) Variables are names for values. In Python the = symbol assigns the value on the right to the name on the left. The variable is created when a value is assigned to it. Here, Python assigns an age to a variable age and a ...

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

  9. Python Assignment Operator

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

  10. Python

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

  11. 7. Simple statements

    Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are 'simultaneous' (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2]:

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

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

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

  15. What does colon equal (:=) in Python mean?

    116. This symbol := is an assignment operator in Python (mostly called as the Walrus Operator ). In a nutshell, the walrus operator compresses our code to make it a little shorter. Here's a very simple example: # without walrus. n = 30. if n > 10: print(f"{n} is greater than 10") # with walrus.

  16. Variables & Assignment

    Valid Names for Variables . A variable name may consist of alphanumeric characters (a-z, A-Z, 0-9) and the underscore symbol (_); a valid name cannot begin with a numerical value.var: valid _var2: valid. ApplePie_Yum_Yum: valid. 2cool: invalid (begins with a numerical character). I.am.the.best: invalid (contains .. They also cannot conflict with character sequences that are reserved by the ...

  17. Different Assignment operators in Python

    Assignment operators in Python are in-fix which are used to perform operations on variables or operands and assign values to the operand on the left side of the operator. They perform arithmetic, logical, and bitwise computations. Assignment Operators in Python. Simple assignment operator in Python; Add and equal operator; Subtract and equal ...

  18. What is Assignment Operator in Python?

    The assignment operator in Python is used as the "=" symbol. Let's see a very basic example of the assignment operator. Table Of Assignment Operators. Here we will see different assignment operators in Python with their names, descriptions, and syntax. Let's take them one by one. Operator Name

  19. Python Operators

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

  20. Assignment Operators in Python

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

  21. Multiple assignment and evaluation order in Python

    See also Multiple assignment semantics regarding the effect and purpose of parentheses on the left-hand side of a multiple assignment. See also Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b? for more complex cases, where the order of assignment matters.

  22. How to Approach Solving Programming Assignments in Python

    Python's built-in sum() function makes this task straightforward and efficient. Computing the Mean. The compute_mean(list_of_numbers) function calculates the mean by dividing the sum of the numbers by the length of the list. def compute_mean(list_of_numbers): """ Computes the mean of the list of numbers.

  23. assignment in python

    This brings the question: is it possible to have proper assignment in python, eg make an object equal to another object? Yes you can: a.__dict__ = dict(b.__dict__) will do the default assignment semantic in C/C++ (i.e. do a shallow assignment). The problem with such generalized assignment is that it never works for everybody.

  24. Disturbing behavior of assignment expressions in comprehensions

    the assignment expression's variable j is not visible in the if-clause and thus a global variable is used, the assignment expression leaks the assigned variable into the global namespace. As a result, the value of j used in the if-clause is not the one from the current iteration, but rather that from the previous iteration.