Introduced in Python 3.8, assignment expressions utilizing the "walrus" operator (:=) provide a significant language enhancement, enabling assignments within comprehensions and lambdas.
An assignment expression is a named expression of the form name := expr, where name is an identifier and expr is any valid expression. The expression evaluates to the value of expr, while simultaneously assigning that value to name.
The primary motivation for adding assignment expressions was to:
a) Obtaining Conditional Values
Instead of:
<code class="python">command = input("> ") while command != "quit": print("You entered:", command) command = input("> ")</code>
Assignment expressions allow:
<code class="python">while (command := input("> ")) != "quit": print("You entered:", command)</code>
b) Simplifying List Comprehensions
Example:
<code class="python">[(lambda y: [y, x/y])(x+1) for x in range(5)]</code>
Can be simplified to:
<code class="python">[[y := x+1, x/y] for x in range(5)]</code>
Assignment expressions differ from regular assignments in several aspects:
The above is the detailed content of What are Assignment Expressions and How Do They Work in Python?. For more information, please follow other related articles on the PHP Chinese website!