assignment expression
In Python, an assignment expression is an assignment that returns a value. You perform this type of assignment using the walrus operator (:=
), which allows you to assign a value to a variable as part of an expression.
Assignment expressions can make your code more concise and readable. They’re particularly useful in situations where you want to assign a value to a variable and then immediately use that value, such as in loops or conditional statements.
Example
Here’s an example of an assignment expression in a while
loop:
>>> values = [10, 20, 0, 30]
>>> while (n := len(values)) > 0:
... print(f"Current list length: {n}")
... values.pop()
...
Current list length: 4
30
Current list length: 3
0
Current list length: 2
20
Current list length: 1
10
In this example, the assignment expression n := len(values)
assigns the length of values
to n
and immediately uses it in the condition of the while
loop. This eliminates the need for a separate line to assign the length to n
, making the code more concise.
Related Resources
Tutorial
The Walrus Operator: Python's Assignment Expressions
In this tutorial, you'll learn about assignment expressions and the walrus operator. The biggest change back in Python 3.8 was the inclusion of the := operator, which you can use to assign variables in the middle of expressions. You'll see several examples of how to take advantage of this feature.
For additional information on related topics, take a look at the following resources:
- Operators and Expressions in Python (Tutorial)
- Expression vs Statement in Python: What's the Difference? (Tutorial)
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- Python Assignment Expressions and Using the Walrus Operator (Course)
- The Walrus Operator: Python's Assignment Expressions (Quiz)
- Python Operators and Expressions (Quiz)
- Expression vs Statement in Python: What's the Difference? (Quiz)
- Mastering While Loops (Course)
- Python while Loops: Repeating Tasks Conditionally (Quiz)
By Leodanis Pozo Ramos • Updated June 20, 2025