Skip to main content

Command Palette

Search for a command to run...

Walrus Operator

Published
•2 min read•View as Markdown
Walrus Operator

The Walrus operator, also known as the "assignment expression," is a new feature introduced in Python 3.8. It allows you to assign a value to a variable as part of an expression, which can help simplify your code and make it more readable.

The syntax of the Walrus operator is as follows: :=

Here's a simple example:

# Using the Walrus operator to assign a value to a variable and check its truth value in the same expression
while (line := input("Enter a line (or 'q' to quit): ")) != 'q':
    print(f"You entered: {line}")

In this example, we use the Walrus operator to assign the result of the input() function to the variable line, and also check its truth value in the same expression. The loop will continue until the user enters the letter "q".

Another example of using the Walrus Operator in an if statement:

names = ["John", "Jane", "Jim"] 
if (name := input("Enter a name: ")) in names:
    print(f"Hello, {name}!")
else:
    print("Name not found.")

One thing to keep in mind when using the Walrus operator is that it can lead to code that's more concise but less readable if used excessively. It's important to strike a balance between using the Walrus operator and using traditional assignment statements and conditionals.

Overall, the Walrus operator is a powerful new feature in Python 3.8 that can help simplify code and make it more readable. It's a great addition to the language and is worth exploring further.

More from this blog

Learning in Public

32 posts