Home > Article > Backend Development > What are Assignment Expressions and How Do They Work in Python 3.8?
Python 3.8 introduced a new concept known as "assignment expressions" using the ":=" operator, commonly referred to as the "walrus" operator.
An assignment expression takes the form name := expr, where expr is any valid Python expression and name is an identifier. The semantics are that the expression's value is assigned to name, and the value of the assignment expression is also the same as expr.
The primary motivation for introducing assignment expressions was to enable assignments within constructs like list comprehensions and lambda functions that previously forbade them. It also facilitates interactive debugging without the need for code refactoring.
a) Getting Conditional Values:
Before:
<code class="python">command = input("> ") while command != "quit": print("You entered:", command) command = input("> ")</code>
After:
<code class="python">while (command := input("> ")) != "quit": print("You entered:", command)</code>
b) Simplifying List Comprehensions:
Before:
<code class="python">[(lambda y: [y, x/y])(x+1) for x in range(5)]</code>
After:
<code class="python">[[y := x+1, x/y] for x in range(5)]</code>
Assignment expressions differ from regular assignments in several ways:
The above is the detailed content of What are Assignment Expressions and How Do They Work in Python 3.8?. For more information, please follow other related articles on the PHP Chinese website!