Basics of the Walrus Operator in Python

Coldstart Coder
2 min readNov 1, 2023

--

One of the strangest operators in Python is the Walrus Operator :=

The purpose of the walrus operator is 2 fold.

  1. Assign a value to a variable
  2. immediately use that variable in a function call

So with the walrus operator these 2 pieces of code are equivalent:

# regular variable assignment
a = "Hello, World!"
print(a)

# Walrus operator assignment
print(b := "Hello, World!")

# for validation and showing that a and b have the same value
print(a == b) # outputs: True

Both a and b have the value “Hello, World!” at the end of execution, but with the walrus operator it was done in a single line instead of 2.

With the walrus operator it reduces the number of lines of code and streamlines the assignment and usage of variables. The Walrus operator works in loops, list operations, and function calls.

# walrus operator as part of a control for a loop
while (user_input := input("Say something: ")) != "Exit":
print("what you said (but backwards)", user_input[::-1]

# using in list operations, creating a variable inline and
# then referencing in other points in the list
my_list = [
value:=5,
value*2,
value**2
]
print(my_list) # output: [5, 10, 25]

# using in a function call
def my_function(i):
return i**5
output = my_function(user_input:=5)
print("the input was %s, the output was %s"%(user_input, output))

An important thing to note is that the walrus operator cannot be used in isolation. It has to be used in a combination with some other operation. The following code will throw an error if you try to run it:

# this will error out
variable := 5

So that’s the basics of the Walrus Operator. It’s an unique operator and has some interesting uses. There are some arguments on when or even if it should be used and how it impacts code readability. However regardless of which camp you are in it’s important to at least know this operator exists and how it works in case you see it in the wild.

Happy Coding!

--

--