Search⌘ K
AI Features

First Things First!

Explore how to use Python's Walrus operator introduced in version 3.8 to assign values within expressions effectively. Understand syntax rules and limitations like parenthesizing restrictions and why some forms cause errors. This lesson helps you write cleaner, more concise code using assignment expressions.

We'll cover the following...

Python 3.8’s “Walrus” operator (:=) was quite popular. Let’s check it out.

C++
a = "ftw_walrus"
print(a)
C++
a := "ftw_walrus" # doesn't work
C++
(a := "ftw_walrus") # This works though
print(a)

Explanation

The Walrus operator (:=) was introduced in Python 3.8, it can be useful in situations where you’d want to assign values to variables within an expression. For instance:

C++
def some_func():
# Assume some expensive computation here
# time.sleep(1000)
return 5
# So instead of,
if some_func():
print(some_func()) # Which is bad practice since computation is happening twice
# or
a = some_func()
if a:
print(a)
# Now you can concisely write
if a := some_func():
print(a)

This saved one line of code, and implicitly prevented invoking some_func twice. Now coming back to an explanation of the snippets:

  • Non-parenthesized “assignment expression” (use of the walrus operator) is restricted at the top level, hence the SyntaxError in the a := "ftw_walrus" statement of the code above. Parenthesizing it worked as expected and assigned a.

  • As usual, parenthesizing an expression containing the = operator is not allowed. Hence, there will be a syntax error in (a, b = 6, 9).

  • The syntax of the Walrus operator is of the form NAME:= expr, where NAME is a valid identifier, and expr is a valid expression.

  • Hence, iterable packing and unpacking are not supported, which means that (a := 6, 9) is equivalent to ((a := 6), 9), and ultimately to (a, 9) (where a's value is 6).

C++
print((a := 6, 9) == ((a := 6), 9))
x = (a := 696, 9)
print(x)
print(x[0] is a) # Both reference same memory location
  • Similarly, (a, b := 16, 19) is equivalent to (a, (b := 16), 19), which is nothing but a 3-tuple.