CodeBlessU
learn code with examples

Assignment Expression in Python

Assignment Expression :=

Python 3.8 introduced Assignment Expression. It is used to assign name to intermediate result within an expression.

Syntax:
name := expression
Note: Outer expression to be continued further by adding small brackets.
# Example, Python Assignment Expression
regular, onetime, max_discount = 10, 95, 90
if (discount := regular + onetime) > max_discount:
   print(f"Warning: discount {discount} is higher than maximum limit.")

Walrus Operator :=

Assignment expression is also known as walrus operator. Reason being, this symbol is matching to walrus eyes and tusks.

When Assignment Expression := shall be used

Python PEP 572 suggests to use assignment expression for intuitive cases. Example:

  • Get some result from if condition expression and use it within if-else block.
  • Extract value from regular expression with condition check and then to use.
  • Get some result within list comprehensions and use it in further processing.

# Examples, Python Assignment Expression

# Example-1, Use assignment expression in if block
regular, onetime, max_discount = 10, 95, 90
if (discount := regular + onetime) > max_discount:
   print(f"Warning: discount {discount} is higher than maximum limit.")

# Example-2, use assignment expression in regular expression
import re
my_string = "99999 dollars"
if (number := re.search(r'(\d+)', my_string)):
   print(f"Extracted number is {number.group()}")

# Example-3, use assignment expression in list comprehensions
names = [" Code ", " Bless", " U", "CodeBlessU"]
names_startswith_c = [ name_without_space.lower() 
  for name in names if (name_without_space := name.strip()).startswith("C") is True]
print(names_startswith_c)

SyntaxError: assignment expression cannot rebind comprehension iteration variable

If left side of assignment expression contains name which is same as other local variable (here iteration variable), you will receive this error.

# Example,

[i := 0 for i, j in stuff] # raises error

SyntaxError: cannot use assignment expressions

You are trying to assign name using assignment expression but overall expression is not correct, you will receive this error. It can be resolved by adding small brackets around assignment expression.

# Example,

(lambda: x := 1) # raises error
(lambda: (x := 1) ) # does not raise error

Cases not suitable for Assignment Expression

Below cases are not suitable for assignment expression

  • Multiple targets like a = b = c = 5
  • Single assignment target, but name is something other than plain name(example, list index position OR object member).

# Example,

a = [1,2,3]
a[0] := 5 # Raises error

How to assign Tuple using Assignment Expression

It is necessary to use small brackets while assigning tuple. Otherwise only first element of tuple will be assigned to name (and full tuple will not be assigned.)

# Example,

x = 1, 2  # creates tuple
print(x)
(x := 1, 2 )  # prints tuple on screen, but x is assigned 1.
print(x)
(x := (1, 2) ) # creates x as tuple
print(x)

In this page...

Copyright © All rights reserved.