Python Walrus Operator: An Introduction to the Assignment Expression in Python

avatar

What is the Walrus Operator?

  • In a Conditional Statement
  • Lists and Dictionaries

Benefits of the Walrus Operator

  • Python Version Compatibility

As a Python developer, you are always looking for ways to write more concise and expressive code. One of the exciting features introduced in Python 3.8 is the Walrus Operator, also known as the Assignment Expression. In this blog post, we'll explore the walrus operator, its usage, benefits, drawbacks, and best practices for using assignment expressions in your Python code.

The walrus operator ( := ) is a new syntax introduced in Python 3.8 through PEP 572 that allows you to assign a value to a variable as part of an expression. The operator gets its name from the eyes and tusks of a walrus, resembling the shape of := .

Before the introduction of the walrus operator, you would need to assign a value to a variable before using it in an expression. With the walrus operator, you can perform the assignment and expression evaluation in a single step. This simplifies your code and makes it more concise and readable.

Benefits and Usage of the Walrus Operator

The walrus operator offers several benefits and can be used in various scenarios to improve code clarity and efficiency.

Examples of How to Use the Walrus Operator

The walrus operator can be used in different contexts, such as loops, conditional statements, and dictionary construction. Here are a few examples:

In this example, the walrus operator is used to simultaneously read a line from the user and check if it's empty. The loop continues until the user enters an empty line, and each non-empty line is added to the lines list.

In a Conditional Statement:

In this case, the walrus operator is used to compute the length of the string and store it in the length variable. The length is then compared to max_length to determine if it exceeds the limit. If it does, a message is printed.

Lists and Dictionaries:

This section demonstrates the utilization of the walrus operator to efficiently compute statistical measures for a list of numbers and construct a dictionary. By employing the walrus operator, the code succinctly assigns the sum and length of the numbers list to variables num_sum and num_length respectively, while simultaneously creating the corresponding key-value pairs in the data dictionary. This concise approach simplifies the code structure, enhances readability, and eliminates the need for separate variable assignments.

The walrus operator provides several benefits:

Concise and Readable Code : With the walrus operator, you can perform assignments within expressions, reducing the need for separate lines of code. This results in more concise and readable code, especially in scenarios where you need to use a variable immediately after assigning a value to it.

Improved Performance : By combining assignment and expression evaluation, you avoid redundant computations. This can be particularly useful when working with expensive function calls or complex expressions.

Despite the value provided by the walrus operator, it is important to carefully consider its usage due to a factors like Python version compatibility and support for type hints.

Python version Compatibility

The walrus operator was introduced in Python 3.8. If you are working on a project that needs to support earlier versions of Python, it's crucial to consider compatibility and provide fallback solutions when necessary.

When using the walrus operator, the assigned value is determined dynamically at runtime, making it challenging to provide type hints directly for the assigned value. The walrus operator is primarily designed to improve code readability and simplify expressions by allowing variable assignment within an expression itself.

However, it's worth noting that you can still use type hints for the variables that are assigned using the walrus operator. For example, you can annotate the variable before the assignment statement, and the type hint will be applicable to the variable:

In the above example, the type hint int is provided for the variable result before the assignment statement using the walrus operator. Although the walrus operator itself doesn't directly support type hints, you can apply type hints to variables in the surrounding context.

The walrus operator, or assignment expression, introduced in Python 3.8, provides a powerful and concise way to assign values to variables as part of an expression. By using the walrus operator, you can simplify your code, improve its readability, and eliminate redundant computations.

Python's walrus operator offers a valuable tool for streamlining your code and making it more expressive. By using it judiciously and in alignment with best practices, you can take advantage of its benefits and enhance your Python programming experience.

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

Python Assignment Operators

Assignment operators in python.

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

Python Relational Operators

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

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

Here are the Assignment Operators in Python with examples.

Assignment Operator

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

Addition Assignment Operator

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

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

S ubtraction Assignment Operator

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

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

M ultiplication Assignment Operator

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

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

D ivision Assignment Operator

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

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

M odulus Assignment Operator

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

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

F loor Division Assignment Operator

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

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

Exponentiation Assignment Operator

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

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

Bitwise AND Assignment Operator

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

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

Bitwise OR Assignment Operator

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

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

Bitwise XOR Assignment Operator 

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

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

Bitwise Right Shift Assignment Operator

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

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

Bitwise Left Shift Assignment Operator

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

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

Walrus Operator

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

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

Please Login to comment...

Similar reads.

author

  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

5. Assignment Expressions

By Bernd Klein . Last modified: 30 Nov 2023.

On this page ➤

Introduction

walrus

This section in our Python tutorial explores the "assignment expression operator" affectionately known to many as "the walrus operator. So, you can call it either the "walrus operator" or the "assignment expression operator," and people in the Python programming community will generally understand what you mean. Despite being introduced in Python version 3.8, we can still view it as a relatively recent addition to the language. The assignment expressions have been discussed in PEP 572 and this is what was written about the naming:

The purpose of this feature is not a new way to assign objects to variables, but it gives programmers a convenient way to assign variables in the middle of expressions.

You might still be curious about the origin of the term "walrus operator." It's affectionately named this way because, with a touch of imagination, the operator's characters resemble the eyes and tusks of a walrus.

We will introduce the assignment expression by comparing it first with a simple assignment statement. A simple assignment statement can also be replaced by an assignment expression, even though it looks clumsy and is definitely not the intended use case of it:

First you may wonder about the brackets, when you look at the assignment expression. It is not meant as a replacement for the simple "assignment statement". Its primary role is to be utilized within expressions

The following code shows a proper usecase:

Though you may argue that the following code might be even clearer:

Here's another Python code example that demonstrates a similar scenario. First with the walrus operator:

Now without the walrus operator:

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Beneficial applications

Now, let's explore some examples where the usage of the assignment expression is really beneficial compared to code not using it.

You can observe that if we choose to avoid using the assignment expression in the list comprehension, we would need to call the function twice. So using the assgment expression makes the code in this context more efficient.

Use Case: Regular Expressions

There is also a great advantage when we use regular expressions. Like in our previous examples we present again two similiar code snippets, the first one without and the second one with the walrus operator:

Now, the code using assignment expressions:

Assignment Expression in File Reading

Fixed-width files.

Files in which each line has the same length are often referred to as "fixed-width" or "fixed-length" files. In these files, each line (or record) is structured so that it contains a predefined number of characters, and the fields within the lines have fixed positions. The files can be read by using the read -method and the walrus operator:

Now the same in traditional coding style:

The benefits for the most recent code snippet are

  • It uses a more traditional coding style, which may be more familiar to some developers.
  • It assigns and uses the data variable explicitly, making the code easier to understand for those not familiar with assignment expressions.

However, a significant drawback of this approach is that it requires the explicit assignment and reassignment of the data variable, which can be seen as less concise and somewhat less elegant.

Using readline

Most people use a for loop to iterator over a text file line by line. With the walrus operator, we can also elegantly go through a text using the method readline :

Code snippet using readline but not the assignment expression:

Now with the walrus operator:

Another Use Case

In the chapter on while loops of our Python Tutorial, we had a little number guessing game:

As you can see, we had to initialize guess to zero to be able to enter the loop. We can do the initialization directly in the loop condition with an assignment expression and simplify the whole code by this:

Critiques of the Walrus Operator in Python

the Python walrus

We said in the beginning of this page that some Python programmers longed for this construct for quite a while. One reason why it was not introduced earlier was the fact that it can also be used to write code which is less readable. In fact, the application of the walrus operator contradicts several principles highlighted in the Zen of Python. To grasp these contraventions, let's delve into the ensuing scenarios.

The Zen of Python says "Explicit is better than implicit". The walrus operator violates this requirement of the Zen of Python. This means that explicit operations are always better than implicit operations. The walrus operator assigns a value to a variable and implicitly returns the value as well. Therefore, it does not align with the concept of "Explicit is better than implicit."

The following code snippet is shows an extreme example which is not recommended to use:

What are your thoughts on the following piece of code using the Python assignment operator inside of a print function call?

These Python code snipets certainly violate two other demands of the Zen of Python:

  • Beautiful is Better Than Ugly
  • Complex is Better Than Complicated

The principle "There should be one and preferably only one obvious way to do it" from the Zen of Python emphasizes the importance of having a clear and singular approach. When we have the option to separate assignment and return operations into distinct statements, opting for the less readable and more complex walrus operator contradicts this principle.

Upcoming online Courses

On this page

Mouse Vs Python

Python 101 – Assignment Expressions

Assignment expressions were added to Python in version 3.8 . The general idea is that an assignment expression allows you to assign to variables within an expression.

The syntax for doing this is:

This operator has been called the “walrus operator”, although their real name is “assignment expression”. Interestingly, the CPython internals also refer to them as “named expressions”.

You can read all about assignment expressions in PEP 572 . Let’s find out how to use assignment expressions!

Using Assignment Expressions

Assignment expressions are still relatively rare. However, you need to know about assignment expressions because you will probably come across them from time to time. PEP 572 has some good examples of assignment expressions.

In these 3 examples, you are creating a variable in the expression statement itself. The first example creates the variable match by assigning it the result of the regex pattern search. The second example assigns the variable value to the result of calling a function in the while loop’s expression. Finally, you assign the result of calling f(x) to the variable y inside of a list comprehension.

It would probably help to see the difference between code that doesn’t use an assignment expression and one that does. Here’s an example of reading a file in chunks:

This code will open up a file of indeterminate size and process it 1024 bytes at a time. You will find this useful when working with very large files as it prevents you from loading the entire file into memory. If you do, you can run out of memory and cause your application or even the computer to crash.

You can shorten this code up a bit by using an assignment expression:

Here you assign the result of the read() to data within the while loop’s expression. This allows you to then use that variable inside of the while loop’s code block. It also checks that some data was returned so you don’t have to have the if not data: break stanza.

Another good example that is mentioned in PEP 572 is taken from Python’s own site.py . Here’s how the code was originally:

And this is how it could be simplified by using an assignment expression:

You move the assignment into the conditional statement’s expression, which shortens the code up nicely.

Now let’s discover some of the situations where assignment expressions can’t be used.

What You Cannot Do With Assignment Expressions

There are several cases where assignment expressions cannot be used.

One of the most interesting features of assignment expressions is that they can be used in contexts that an assignment statement cannot, such as in a lambda or the previously mentioned comprehension. However, they do NOT support some things that assignment statements can do. For example, you cannot do multiple target assignment:

Another prohibited use case is using an assignment expression at the top level of an expression statement. Here is an example from PEP 572:

There is a detailed list of other cases where assignment expressions are prohibited or discouraged in the PEP. You should check that document out if you plan to use assignment expressions often.

Wrapping Up

Assignment expressions are an elegant way to clean up certain parts of your code. The feature’s syntax is kind of similar to type hinting a variable. Once you have the hang of one, the other should become easier to do as well.

In this article, you saw some real-world examples of using the “walrus operator”. You also learned when assignment expressions shouldn’t be used. This syntax is only available in Python 3.8 or newer, so if you happen to be forced to use an older version of Python, this feature won’t be of much use to you.

Related Reading

This article is based on a chapter from Python 101, 2nd Edition , which you can purchase on Leanpub or Amazon .

If you’d like to learn more Python, then check out these tutorials:

Python 101 – How to Work with Images

Python 101 – Documenting Your Code

Python 101: An Intro to Working with JSON

Python 101 – Creating Multiple Processes

Assignment expressions in Python

python assignment expressions

A new version of Python just came out (Python 3.8), and that means we get some new toys to play with . One of the interesting new features to come with Python 3.8 was assignment expressions, and the much debated "walrus operator" ( := ). In this post we're going to talk about what assignment expressions are, and how to use them.

Assignment expressions were proposed in PEP 572 , which was a hugely controversial proposal. I actually think assignment expressions are a great addition to the language; however, before we show off what they can do, I can't stress enough that they are really easy to abuse. Just pay extra care that you're not making your code harder to read by using them.

So, what exactly is all this fuss about?

Here is a piece of code from our Complete Python Course , from an exercise where we practice basic loops combined with conditionals:

The code above is fairly simple. We have this while loop which keeps asking the user to press p or q , and if the user pressed p , we print this cheerful little "Hello!" message. If the user presses q , on the other hand, the loop ends. For any other input, we do nothing.

While this code is okay, we do have this annoying bit of duplication, because we have to start up the loop by defining user_input . If we don't, user_input is undefined during the first iteration of the loop.

Now here is the same code using an assignment expression:

As you can see we now have our cute little walrus next to user_input when we define the loop condition, but there's actually quite a lot going on here, so let's break it down.

First of all, what does the := actually do? It's essentially a special type of assignment operator. As usual, we assign some value to a variable name, but the key difference is that the assignment is treated as an expression.

Expressions evaluate to something , and in the case of assignment expressions, the value they evaluate to is the value after the assignment operator, := .

The fact that the assignment is an treated as an expression is why we can use != 'q' directly after it: the assignment expression represents an actual value. This is different from the assignment statements we're used to in Python, which don't represent any value at all.

As you can see in the example above, we have an expression which forms the condition for our while loop which looks like this:

It reads something like, " user_input is not equal to the string 'q' , where user_input is the return value of the function call input('Enter p or q: ') ".

In the case of our while loop, this expression, including the assignment, is evaluated for every iteration of the loop. This means that for every iteration of the loop, we're going to ask the user to enter a value, and that value will be assigned to the variable user_input , and compared against the string 'q' .

Since user_input is just a normal loop variable, we can still use it inside the loop as well, which is why the if statement isn't complaining.

One important part of the syntax here is that the assignment is wrapped in parentheses. This is a requirement in basically all cases where an assignment expression is likely, but you can read more about it in this section of the PEP .

In addition to trimming off a few lines here and there, assignment expressions can also be used to improve the efficiency of our programs by preventing the repetition of costly operations. I think this is most effective in structures like list comprehensions:

Here we're concerned with the values generated by this costly_function when we pass it values from some iterable called data . Instead of calculating the results twice - once when performing the comparison, and once when adding the value to the results list - we now just assign the result to a variable and reference the variable.

The alternative would be something like this:

It's quite a lot more verbose, but perhaps that verbosity is worth it for the kind of clarity we get with the traditional for loop. It's really up to you to decide whether or not the assignment expressions are readable enough to justify the reduction in code length.

I'd really recommend taking a look at some of the examples in the PEP, in addition to their advice on using the syntax well. It's really not worth putting assignment expressions all over the place, as it's only going to harm the readability of your code. It's an effective but quite niche tool that we all need to be very careful with.

Wrapping up

That's it for this post on assignment expressions! We'd love to know what you think of the new syntax, so get in touch with us on Twitter , or join us over on Discord .

We'll be adding plenty of content to our blog in the near future covering interesting additions that came with Python 3.8, so make sure you stay up to date with all our content by signing up to our mailing list below. We'll also be adding new lectures to our Complete Python Course as well, so stay tuned!

David Muller My book: Intuitive Python ↗

How to use assignment expressions in python.

10 November, 2020

This article was originally published in DigitalOcean’s public knowledge base . It has been reproduced here with some minor edits.

Introduction

Python 3.8 , released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called “the walrus operator” because := vaguely resembles a walrus with tusks.

Assignment expressions allow variable assignments to occur inside of larger expressions. While assignment expressions are never strictly necessary to write correct Python code, they can help make existing Python code more concise. For example, assignment expressions using the := syntax allow variables to be assigned inside of if statements, which can often produce shorter and more compact sections of Python code by eliminating variable assignments in lines preceding or following the if statement.

In this tutorial, you will use assignment expressions in several examples to produce concise sections of code.

Prerequisites

To get the most out of this tutorial, you will need:

  • Python 3.8 or above. Assignment expressions are a new feature added starting in Python 3.8.

Using Assignment Expressions in if Statements

Let’s start with an example of how you can use assignment expressions in an if statement.

Consider the following code that checks the length of a list and prints a statement:

If you run the previous code, you will receive the following output:

You initialize a list named some_list that contains three elements. Then, the if statement uses the assignment expression ((list_length := len(some_list)) to bind the variable named list_length to the length of some_list . The if statement evaluates to True because list_length is greater than 2 . You print a string using the list_length variable, which you bound initially with the assignment expression, indicating the the three-element list is too long.

Note: Assignment expressions are a new feature introduced in Python 3.8 . To run the examples in this tutorial, you will need to use Python 3.8 or higher.

Had we not used assignment expression, our code might have been slightly longer. For example:

This code sample is equivalent to the first example, but this code requires one extra standalone line to bind the value of list_length to len(some_list) .

Another equivalent code sample might just compute len(some_list) twice: once in the if statement and once in the print statement. This would avoid incurring the extra line required to bind a variable to the value of len(some_list) :

Assignment expressions help avoid the extra line or the double calculation.

Note: Assignment expressions are a helpful tool, but are not strictly necessary. Use your judgement and add assignment expressions to your code when it significantly improves the readability of a passage.

In the next section, we’ll explore using assignment expressions inside of while loops.

Using Assignment Expressions in while Loops

Assignment expressions often work well in while loops because they allow us to fold more context into the loop condition.

Consider the following example that embeds a user input function inside the while loop condition:

If you run this code, Python will continually prompt you for text input from your keyboard until you type the word stop . One example session might look like:

The assignment expression (directive := input("Enter text: ")) binds the value of directive to the value retrieved from the user via the input function. You bind the return value to the variable directive , which you print out in the body of the while loop. The while loop exits whenever the you type stop .

Had you not used an assignment expression, you might have written an equivalent input loop like:

This code is functionally identical to the one with assignment expressions, but requires four total lines (as opposed to two lines). It also duplicates the input("Enter text: ") call in two places. Certainly, there are many ways to write an equivalent while loop, but the assignment expression variant introduced earlier is compact and captures the program’s intention well.

So far, you’ve used assignment expression in if statements and while loops. In the next section, you’ll use an assignment expression inside of a list comprehension.

Using Assignment Expressions in List Comprehensions

We can also use assignment expressions in list comprehensions. List comprehensions allow you to build lists succinctly by iterating over a sequence and potentially adding elements to the list that satisfy some condition.

Consider the following example that uses a list comprehension and an assignment expression to build a list of multiplied integers:

If you run the previous code, you will receive the following:

You define a function named slow_calculation that multiplies the given number x with itself. A list comprehension then iterates through 0 , 1 , and 2 returned by range(3) . An assignment expression binds the value result to the return of slow_calculation with i . You add the result to the newly built list as long as it is greater than 0. In this example, 0 , 1 , and 2 are all multiplied with themselves, but only the results 1 ( 1 * 1 ) and 4 ( 2 * 2 ) satisfy the greater than 0 condition and become part of the final list [1, 4] .

The slow_calculation function isn’t necessarily slow in absolute terms, but is meant to illustrate an important point about effeciency. Consider an alternate implementation of the previous example without assignment expressions:

Running this, you will receive the following output:

In this variant of the previous code, you use no assignment expressions. Instead, you call slow_calculation up to two times: once to ensure slow_calculation(i) is greater than 0 , and potentially a second time to add the result of the calculation to the final list. 0 is only multiplied with itself once because 0 * 0 is not greater than 0 . The other results, however, are doubly calculated because they satisfy the greater than 0 condition, and then have their results recalculated to become part of the final list [1, 4] .

You’ve now combined assignment expressions with list comprehensions to create blocks of code that are both efficient and concise.

In this tutorial, you used assignment expressions to make compact sections of Python code that assign values to variables inside of if statements, while loops, and list comprehensions.

For more information on other assignment expressions, you can view PEP 572 —the document that initially proposed adding assignment expressions to Python.

Editor: Kathryn Hancox

davidmuller.github.io / Home / My book: Intuitive Python ↗

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 379 – Adding an Assignment Expression

Motivation and summary, specification, examples from the standard library.

This PEP adds a new assignment expression to the Python language to make it possible to assign the result of an expression in almost any place. The new expression will allow the assignment of the result of an expression at first use (in a comparison for example).

Issue1714448 “if something as x:” [1] describes a feature to allow assignment of the result of an expression in an if statement to a name. It supposed that the as syntax could be borrowed for this purpose. Many times it is not the expression itself that is interesting, rather one of the terms that make up the expression. To be clear, something like this:

seems awfully limited, when this:

is probably the desired result.

See the Examples section near the end.

A new expression is proposed with the (nominal) syntax:

This single expression does the following:

  • Evaluate the value of EXPR , an arbitrary expression;
  • Assign the result to VAR , a single assignment target; and
  • Leave the result of EXPR on the Top of Stack (TOS)

Here -> or ( RARROW ) has been used to illustrate the concept that the result of EXPR is assigned to VAR .

The translation of the proposed syntax is:

The assignment target can be either an attribute, a subscript or name:

This expression should be available anywhere that an expression is currently accepted.

All exceptions that are currently raised during invalid assignments will continue to be raised when using the assignment expression. For example, a NameError will be raised when in example 1 and 2 above if name is not previously defined, or an IndexError if index 0 was out of range.

The following two examples were chosen after a brief search through the standard library, specifically both are from ast.py which happened to be open at the time of the search.

Using assignment expression:

The examples shown below highlight some of the desirable features of the assignment expression, and some of the possible corner cases.

  • Assignment in an if statement for use later: def expensive (): import time ; time . sleep ( 1 ) return 'spam' if expensive () -> res in ( 'spam' , 'eggs' ): dosomething ( res )
  • Assignment in a while loop clause: while len ( expensive () -> res ) == 4 : dosomething ( res )
  • Keep the iterator object from the for loop: for ch in expensive () -> res : sell_on_internet ( res )
  • Corner case: for ch -> please_dont in expensive (): pass # who would want to do this? Not I.

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0379.rst

Last modified: 2023-09-09 17:39:29 GMT

python assignment expressions

Refactor your code with C# collection expressions

python assignment expressions

May 8th, 2024 7 8

This post is the second in a series of posts covering various refactoring scenarios that explore C# 12 features. In this post, we’ll look at how you can refactor your code using collection expressions, we’ll learn about collection initializers, various expression usages, supported collection target types, and the spread syntax. Here’s how the series is shaping up:

  • Refactor your C# code with primary constructors
  • Refactor your C# code with collection expressions (this post)
  • Refactor your C# code by aliasing any type
  • Refactor your C# code to use default lambda parameters

These features continue our journey to make our code more readable and maintainable, and these are considered “Everyday C#” features that developers should know.

Collection Expressions 🎨

C# 12 introduced collection expressions that offer a simple and consistent syntax across many different collection types. When initializing a collection with a collection expression, the compiler generates code that is functionally equivalent to using a collection initializer. The feature emphasizes consistency , while allowing for the compiler to optimize the lowered C#. Of course, every team decides what new features to adopt, and you can experiment and introduce this new syntax if you like it, since all of the previous ways to initialize collections will continue to work.

With collections expressions elements appear inlined sequences of elements between an opening [ and closing ] bracket. Read on to hear more about how collection expressions work.

Initialization 🌱

C# provides many syntaxes for initializing different collections. Collection expressions replace all of these, so let’s start with a look at different ways you can initialize an array of integers like this:

All four versions are functionally equivalent, and the compiler generates identical code for each version. The last example is similar to the new collection expressions syntax. If you squint your eyes a bit, you could imagine the curly braces as { and } as square brackets [ and ] , then you’d be reading the new collection expression syntax. Collection expressions don’t use curly braces. This is to avoid ambiguity with existing syntax, especially { } to indicate any not-null in patterns.

The last example is the only to declare the type explicitly, instead of relying on var . The following example creates a List<char> :

Again, collection expressions cannot be used with the var keyword. You must declare the type because a collection expression doesn’t currently have a natural type and can be converted to a wide variety of collection types . Supporting assignment to var is still under consideration, but the team has not settled on the what the natural type should be. In other words, the C# compiler errors out with CS9176: There is no target type for the collection expression, when writing the following code:

You might be asking yourself, “with all these different approaches to initializing collections, why would I use the new collection expression syntax?” The answer is that with collection expressions, you can use the same syntax to express collections in a consistent way. This can help to make your code more readable and maintainable. We’ll explore more advantages in the coming sections.

Collection expression variations 🎭

You can express that a collection is empty , using the following syntax:

The empty collection expression initialization is a great replacement for code that was otherwise using the new keyword, as it’s optimized by the compiler to avoid allocating memory for some collection types. For example, when the collection type is an array T[] , the compiler generates an Array.Empty<T>() , which is more efficient than new int[] { } . Another shortcut is to use the number of elements in the collection expression to set the collection size, such as new List<int>(2) for List<T> x = [1, 2]; .

Collection expressions also allow you to assign to interfaces without stating an explicit type. The compiler determines the type to use for types, such as IEnumerable<T> , IReadOnlyList<T> , and IReadOnlyCollection<T> . If the actual type used is important, you’ll want to state it because this may change if more efficient types become available. Likewise, in situations where the compiler cannot generate more efficient code, for example when the collection type is a List<T> , the compiler generates a new List<int>() , which is then equivalent.

The advantages of using the empty collection expression are threefold:

  • It provides a consistent means of initializing all collections, regardless of their target type.
  • It allows the compiler to generate efficient code.
  • It’s less code to write. For example, instead of writing Array.Empty<T>() or Enumerable.Empty<T>() , you can simply write [] .

A few more details about the efficient generated code: using the [] syntax generates known IL. This allows the runtime to optimize by reusing the storage for Array.Empty<T> (for each T ), or even more aggressively inline the code.

Empty collections serve their purpose, but you may need a collection that has some initial values. You can initialize a collection with a single element, using the following syntax:

Initializing a single element collection is similar to initializing a collection with more than a single element. You can initialize a collection with multiple elements by adding other literal values, using the following syntax:

A bit of history

Let’s look at another code sample, but this uses spread element , to include the elements of another collection, using the following syntax:

The spread element is a powerful feature that allows you to include the elements of another collection in the current collection. The spread element is a great way to combine collections in a concise way. The expression in a spread element must be enumerable ( foreach -able). For more information, see the Spread ✨ section.

Supported collection types 🎯

There are many target types that collection expressions can be used with. The feature recognizes the “shape” of a type that represents a collection. Therefore, most collections you’re familiar with are supported out-of-the-box. For types that don’t match that “shape” (mostly readonly collections), there are attributes you can apply to describe the builder pattern. The collection types in the BCL that needed the attributes/builder pattern approaches, have already been updated.

It’s unlikely that you’ll ever need to think about how target types are selected, but if you are curious about the rules see the C# Language Reference: Collection expressions—conversions .

Collection expressions don’t yet support dictionaries. You can find a proposal to extend the feature C# Feature Proposal: Dictionary expressions .

Refactoring scenarios 🛠️

Collection expressions can be useful in many scenarios, such as:

  • properties.
  • local variables.
  • method parameters.
  • return values.
  • a coalescing expression as the final fallthrough to safely avoid exceptions.
  • Passing arguments to methods that expect collection type parameters.

Let’s use this section to explore some sample usage scenarios, and consider potential refactoring opportunities. When you define a class or struct that contains fields and/or properties with non-nullable collection types, you can initialize them with collection expressions. For example, consider the following example ResultRegistry object:

In the preceding code, the result registry class contains a private _results field that is initialized with a new HashSet<Result>() constructor expression. In your IDE of choice (that supports these refactoring features), right-click on the new keyword, select Quick Actions and Refactorings... (or press Ctrl + . ), and choose Collection initialization can be simplified , as shown in the following video:

The code is updated to use the collection expression syntax, as shown in the following code:

The previous code, instantiated the HashSet<Result> with the new HashSet<Result>() constructor expression. However, in this case [] is identical.

Many popular programming languages such as Python and JavaScript/TypeScript, among others provide their variation of the spread syntax, which serves as a succinct way to work with collections. In C#, the spread element is the syntax used to express the concatenation of various collections into a single collection.

Proper terminology

So what exactly is spread element ? It takes the individual values from the collection being “spread” and places them in the destination collection at that position. The spread element functionality also comes with a refactoring opportunity. If you have code that calls .ToList or .ToArray , or you want to use eager evaluation, your IDE might be suggesting to use the spread element syntax instead. For example, consider the following code:

The preceding code could be refactored to use the spread element syntax, consider the following code that removes the .ToList method call, and uses an expression-bodied method as a bonus refactored version:

Span<T> and ReadOnlySpan<T> support 📏

Collection expressions support Span<T> and ReadOnlySpan<T> types that are used to represent a contiguous region of arbitrary memory. You benefit from the performance improvements they offer, even if you don’t use them directly in your code. Collection expressions allow the runtime to offer optimizations, especially where overloads using span can be selected when collection expressions are used as arguments.

You can also assign directly to span, if your application uses spans:

If you’re using the stackalloc keyword, there’s even a provided refactoring to use collection expressions. For example, consider the following code:

If you right-click on the stackalloc keyword, select Quick Actions and Refactorings... (or press Ctrl + . ), and choose Collection initialization can be simplified , as shown in the following video:

https://devblogs.microsoft.com/dotnet/wp-content/uploads/sites/10/2024/05/refactor-collection-ex.mp4

For more information, see Memory<T> and Span<T> usage guidelines .

Semantic considerations ⚙️

When initializing a collection with a collection expression, the compiler generates code that is functionally equivalent to using a collection initializer. Sometimes the generated code is much more efficient than using a collection initializer. Consider the following example:

The rules for a collection initializer require that the compiler call the Add method for each element in the initializer. However, if you’re to use the collection expression syntax:

The compiler generates code that instead uses AddRange , that might be faster or better optimized. The compiler is able to make these optimizations because it knows the target type of the collection expression.

Next steps 🚀

Be sure to try this out in your own code! Check back soon for the next post in this series, where we’ll explore how to refactor your C# code by aliasing any type. In the meantime, you can learn more about collection expressions in the following resources:

  • C# Feature Proposal: Collection expressions
  • C# Language Reference: Collection expressions
  • C# Docs: Collections

python assignment expressions

David Pine Senior Content Developer, .NET

python assignment expressions

Leave a comment Cancel reply

Log in to join the discussion or edit/delete existing comments.

This is all extremely nice!

This is a neat implementation of the Collection expression.

IMHO this is the annoying part of the feature Again, collection expressions cannot be used with the var keyword.

hope this will be addressed sooner then later, and if that’s all the reason behind it but the team has not settled on the what the natural type should be.

roll a dice if you can’t make up your mind. Or put up a poll and let majority decide.

I disagree. var support is not needed.

If anyone is wondering, the question is which is the correct choice when var is used: a) Default to the fastest and most efficient, such as Span or ReadOnlySpan b) Default to the one with the best developer experience, such as List

You can argue both cases, so it is just hard for everyone to reach agreement here.

Love or hate the collection expressions, but the use of emojis here is world class.

Regarding the LINQ example with the spread operator: does use of the collection expression result in the same call to .ToList() or is there some additional optimization going on? The original code could have been written as expression-bodied member as well, without declaring a local variable, so the new syntax isn’t much shorter and arguably the intent isn’t really clearer either. I wouldn’t use collection expressions in that case, unless perhaps it’s more efficient – hence the question.

(that aside, a very useful feature! the spread operator will replace a bunch of help methods in our code that were used to combine individual items and lists into a single list in an efficient manner, glad to let the compiler do that now)

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

IMAGES

  1. Python3.8 Assignment expressions using ":="

    python assignment expressions

  2. Learn Python Programming Tutorial 4

    python assignment expressions

  3. Python's assignment expression ("walrus") operator: What, why, and how

    python assignment expressions

  4. Assignment operators in python

    python assignment expressions

  5. Assignment Operators in Python

    python assignment expressions

  6. New Python 3.8 Assignment Expression Feature

    python assignment expressions

VIDEO

  1. Expressions in Python Programming by Utkarsh and Aishwary

  2. L-5.4 Assignment Operators

  3. # python assignment operators # python #hindi #datascience

  4. Python Assignment Operators And Comparison Operators

  5. Prank Your Friends with Rotate Screen on Python

  6. Logical AND & OR Operators in Python

COMMENTS

  1. PEP 572

    Unparenthesized assignment expressions are prohibited for the value of a keyword argument in a call. Example: foo(x = y := f(x)) # INVALID foo(x=(y := f(x))) # Valid, though probably confusing. This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

  2. Assignment Expressions: The Walrus Operator

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

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

  4. The Walrus Operator: Python 3.8 Assignment Expressions

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

  5. python

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

  6. How To Use Assignment Expressions in Python

    Python 3.8, released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called "the walrus operator" because := vaguely resembles a walrus with tusks. Assignment expressions allow variable assignments to occur inside of larger expressions.

  7. Python Walrus Operator: An Introduction to the Assignment Expression in

    The walrus operator, or assignment expression, introduced in Python 3.8, provides a powerful and concise way to assign values to variables as part of an expression. By using the walrus operator, you can simplify your code, improve its readability, and eliminate redundant computations.

  8. PYTHON

    In this tutorial, we will explore the assignment expressions, also known as the walrus operator (:=), in Python. We'll go through the practical applications of the walrus operator and its benefits… Open in app

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

  10. 5. Assignment Expressions

    5. First you may wonder about the brackets, when you look at the assignment expression. It is not meant as a replacement for the simple "assignment statement". Its primary role is to be utilized within expressions. The following code shows a proper usecase: x = 4.56 z = (square := x**2) - (6.6 / square) print(z) OUTPUT:

  11. PYTHON

    Assignment expressions, also known as the walrus operator, are a feature in Python that allow you to assign values to variables within an expression. This article discusses the syntax and usage of assignment expressions in Python. Syntax of Assignment Expressions. The assignment expression uses the := operator, and its syntax is as follows:

  12. PYTHON

    Assignment expressions, also known as the walrus operator (:=), were introduced in Python 3.8. They allow you to assign a value to a variable as part of an expression. This can be particularly useful in simplifying code and making it more readable, especially in cases where you need to perform an expression and then use the result later in the ...

  13. Python 101

    Assignment expressions were added to Python in version 3.8. The general idea is that an assignment expression allows you to assign to variables within an expression. The syntax for doing this is: NAME := expr. This operator has been called the "walrus operator", although their real name is "assignment expression".

  14. Python Assignment Expressions and Using the Walrus Operator (Overview)

    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 course is an in-depth introduction ...

  15. Assignment expressions in Python

    A new version of Python just came out (Python 3.8), and that means we get some new toys to play with. One of the interesting new features to come with Python 3.8 was assignment expressions, and the much debated "walrus operator" (:=). In this post we're going to talk about what assignment expressions are, and how to use them.

  16. How To Use Assignment Expressions in Python

    Python 3.8 or above. Assignment expressions are a new feature added starting in Python 3.8. Using Assignment Expressions in if Statements. Let's start with an example of how you can use assignment expressions in an if statement. Consider the following code that checks the length of a list and prints a statement:

  17. Operators and Expressions in Python

    The walrus operator is also a binary operator. Its left-hand operand must be a variable name, and its right-hand operand can be any Python expression. The operator will evaluate the expression, assign its value to the target variable, and return the value. The general syntax of an assignment expression is as follows:

  18. PEP 379

    The translation of the proposed syntax is: VAR = (EXPR) (EXPR) The assignment target can be either an attribute, a subscript or name: f() -> name[0] # where 'name' exists previously. f() -> name.attr # again 'name' exists prior to this expression. f() -> name. This expression should be available anywhere that an expression is currently accepted ...

  19. python

    I am using mypy for linting and I am getting the following error: Incompatible types in assignment (expression has type "str", variable has type "list[str]"). Full Code: def

  20. Python and Pandas for Data Engineering

    Installing Packages with pip in Python • 6 minutes; Saving Requirements File in Python • 3 minutes; Creating and Using a Python Virtual Environment • 5 minutes; Expression Statements in Python • 3 minutes; Assignment Statements in Python • 5 minutes; Import Statements in Python • 4 minutes; Other Simple Statements in Python • 5 ...

  21. Refactor your code with C# collection expressions

    The .. expression isn't an operator, it's an expression that's part of the spread element syntax. By definition, this syntax doesn't align with that of an operator, as it doesn't perform an operation on its operands. For example, the .. expression already exists with the slice pattern for ranges and it's also found in list patterns.

  22. Assignment Expression Syntax

    Assignment Expression Syntax. For more information on concepts covered in this lesson, you can check out: Walrus operator syntax. One of the main reasons assignments were not expressions in Python from the beginning is the visual likeness of the assignment operator (=) and the equality comparison operator (==). This could potentially lead to bugs.

  23. Assignment Expressions

    Assignment Expressions. For more information on concepts covered in this lesson, you can check out: Here's a feature introduced in version 3.8 of Python, which can simplify the function we're currently working on. It's called an assignment expression, and it allows you to save the return value of a function to a variable while at the same ...