Python Walrus Operator: An Introduction
PGzlan
Posted on October 28, 2023
Python 3.8 introduced a new operator called the walrus operator, denoted by :=
. It's called the Walrus operator because it looks like the eyes and the tusks of a walrus on its side. This operator allows you to evaluate an expression and assign its value to a variable in a single statement.
What is the Walrus Operator?
The walrus operator, also known as the assignment expression operator, is a syntax enhancement that has been introduced in Python 3.8. It allows you to assign a value to a variable within an expression. The syntax for the walrus operator is (variable := expression)
[1].
Basic Usage
Let's start with a basic example to understand how the walrus operator works. Consider the following code snippet:
walrus = (value := 3357)
print(f"walrus: {walrus}")
print(f"value: {value}")
Output:
walrus: 3357
value: 3357
In this example, we use the walrus operator to define the variable value
and assign it the value 3357
. The expression (value := 3357)
returns the assigned value, which we then use to initialize the variable walrus
. As a result, both variables have the same value [1].
Use Cases
1. If Statements
The walrus operator can be useful in if statements when you want to perform an operation on an unknown variable. For example, let's say you want check if a specific environment variable is set and based on that, you want to execute a set of actions. This is one way it could be done conventionally:
import os
import shutil
def delete_folder_contents():
# Get the value of the "PGDATA" environment variable
pgdata_path = os.environ.get("PGDATA", None)
if pgdata_path:
# Verify if the path exists
if os.path.exists(pgdata_path):
# Iterate over the files and folders within the directory
for filename in os.listdir(pgdata_path):
file_path = os.path.join(pgdata_path, filename)
# Check if it is a file and delete it
if os.path.isfile(file_path):
os.remove(file_path)
# Check if it is a directory and delete it recursively
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
print("Folder contents deleted successfully.")
else:
print("The specified path does not exist.")
else:
print("The 'PGDATA' environment variable is not set.")
delete_folder_contents()
Here's how you can achieve this using the walrus operator:
import os
import shutil
def delete_folder_contents():
# Verify if the path exists
if (pgdata_path := os.environ.get("PGDATA", None)) is not None:
# Check if the path exists
if os.path.exists(pgdata_path):
# Iterate over the files and folders within the directory
for filename in os.listdir(pgdata_path):
file_path = os.path.join(pgdata_path, filename)
# Check if it is a file and delete it
if os.path.isfile(file_path):
os.remove(file_path)
# Check if it is a directory and delete it recursively
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
print("Folder contents deleted successfully.")
else:
print("The specified path does not exist.")
else:
print("The 'PGDATA' environment variable is not set.")
delete_folder_contents()
The assignment expression (pgdata_path := os.environ.get("PGDATA", None))
assigns the value of os.environ.get("PGDATA", None)
to pgdata_path
and simultaneously checks if it is not None
. This allows you to combine the assignment and the if
statement in a single line, removing one level of indentation.
2. For Loops
The walrus operator can also be used in for loops. Consider the following example where we want to create a list of squares of numbers in the input list if the squares are greater than 100:
def fibonacci(n):
if 0 <= n < 2:
return n
elif n < 0:
raise ValueError("Negative Fibonnaci not supported")
else:
fib_seq = (0, 1)
for i in range(n - 1):
(fib_seq := (fib_seq[1], sum(fib_seq)))
return fib_seq[1]
n = 10
fib_sequence = fibonacci(n)
print(f"The Fibonacci sequence in the position {n} is: {fib_sequence}")
Output:
The Fibonacci sequence in the position 10 is: 55
In this example, the walrus operator (fib_seq := (fib_seq[1], sum(fib_seq)))
sets the values of the tuple (moves the second item in first position and places the sum of the existing values in the second position) and assigns that tuple to the variable fib_seq
3. List Comprehension
The walrus operator can also be used in list comprehensions to simplify the code. Consider the following example where we want to create a new list of squares of numbers from the input list of prime numbers if the squares are greater than 100:
prime_list = [2, 3, 5, 7, 11]
applicable_list = [psqrd for prime in prime_list if (psqrd := prime ** 2) >= 100]
print("The original list is:", prime_list)
print("The output list is:", applicable_list)
Output:
The original list is: [2, 3, 5, 7, 11]
The output list is: [121]
In this example, the walrus operator (psqrd := prime ** 2)
calculates the square of each number in the input list and assigns it to the variable psqrd
. If the square is greater than or equal to 100, it is added to the applicable_list
[1].
4. While Loops
The walrus operator can also be used in while loops. Consider the following example where we want to read input from a user until they enter the flag \q
'. One way of doing it would be:
data = []
while True:
d = input('Please provide the required data: ')
if d == '\q':
break
data.append(d)
print(f'Data passed is: {data}')
Output:
Please provide the required data: 1
Please provide the required data: 2
Please provide the required data: 3
Please provide the required data: \q
Data passed is: ['1', '2', '3']
We can modify this example to use the walrus operator to simplify the loop by creating the variable passed to input
as well as check its value:
data = []
while (d := input('Please provide the required data: ')) != '\q':
data.append(d)
print(f'Data passed is: {data}')
Output:
Please provide the required data: 1
Please provide the required data: 2
Please provide the required data: 3
Please provide the required data: \q
Data passed is: ['1', '2', '3']
Controversy Surrounding the Walrus Operator
Like any new feature, the walrus operator has sparked some controversy within the Python community. Some developers argue that it violates certain heuristics and can lead to less readable code [2]. However, others find it to be a powerful addition that simplifies certain programming tasks.
Conclusion
The walrus operator might just be a valuable addition to Python's syntax, providing a concise and efficient way to assign and evaluate expressions. While it may be a subject of controversy, it offers developers new possibilities for writing clean and efficient code.
Resources
Posted on October 28, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.