Table of Contents | |
|
What Is Python Walrus Operator?
Python Walrus Operator is a new type of operator introduced in Python 3.8. It’s written as :=
and is formally known as an “assignment expression.” The operator gets its nickname from its resemblance to the eyes and tusks of a walrus. Python Walrus Operator allows you to assign a value to a variable within an expression. This means you can both assign a value and use that value in the same line of code. Before this operator, you would typically need separate lines to assign a value and then use it in a condition or calculation. It simplifies your code and makes it more readable in certain situations.
Python Walrus Operator Syntax
(variable := expression)
Explanation
:=
: This is Walrus Operator.variable
: Variable name you want to assign a value to.expression
: Any valid Python expression that produces a value.()
: The parentheses are often necessary to clearly define the scope of the assignment expression. For example, you might writeif (x := 10) > 5:
, which assigns10
tox
and then checks ifx
is greater than5
.
Example of Python Walrus Operator
n = 15
if (n := n - 5) > 5:
print(f"The value is {n} which is greater than 5")
Explanation
n = 15
: Initialize a variablen
with the value15
.if (n := n - 5) > 5:
: Line uses the Python Walrus Operator.n := n - 5
assigns the result ofn - 5
(which is10
) back ton
.- Entire expression
(n := n - 5)
also evaluates to10
because the value assigned is also returned by the operator. - Then,
> 5
checks if the result (10
) is greater than5
.
print(f"The value is {n} which is greater than 5")
: Since10
is greater than5
, this line is executed, printing the message along with the new value ofn
(which is10
).
Output
The value is 10 which is greater than 5
How and When Python Walrus Operator is Helpful
Python Walrus Operator can be helpful in situations where you need to use a value multiple times within an expression or a block of code, but you only want to calculate it once. Instead of calculating the value in advance and storing it in a separate variable or calculating it repeatedly, the Walrus Operator lets you do both the calculation and the assignment in a single step. This improves code readability by keeping related logic closer together. It’s especially useful when the calculation is part of a condition (like in an if or while statement) or when working with comprehensions or generator expressions.
Example
data = [1, 2, 3, 4, 5]
# Without Walrus
length = len(data)
if length > 3:
print(f"List is long, it has {length} elements")
# With Walrus
if (length := len(data)) > 3:
print(f"List is long, it has {length} elements")
Explanation
data = [1, 2, 3, 4, 5]
: We create a sample list calleddata
.# Without Walrus
: This is a comment indicating the following code does not use the Walrus Operator.length = len(data)
: We calculate the length of the list and store it inlength
.if length > 3:
: We check iflength
is greater than3
.print(f"List is long, it has {length} elements")
: If the condition is true, we print a message.# With Walrus
: This is a comment indicating the following code does use the Walrus Operator.if (length := len(data)) > 3:
: We use the Walrus Operator:=
to assign the length ofdata
tolength
within theif
condition.print(f"List is long, it has {length} elements")
: If the condition is true, we print the same message. The code with the Walrus operator achieves the same result in fewer lines.
Output
List is long, it has 5 elements
List is long, it has 5 elements
Lists and Dictionaries with Python Walrus Operator
When working with lists and dictionaries, the Walrus Operator can streamline code where you need to check for the existence of an element or a key and then use it. Its main advantage is to make your code more concise, especially when you want to check if a key is in a dictionary and perform some operation with its value.
Syntax
# Dictionaries
if (value := my_dict.get(key)) is not None:
# Do something with value
# Lists
if (item := my_list[index]) some_condition:
# Do something with item
Explanation
if (value := my_dict.get(key)) is not None:
: For dictionaries, the Python Walrus Operator:=
assigns the result ofmy_dict.get(key)
tovalue
. We then check ifvalue
is notNone
(meaning the key exists).if (item := my_list[index]) some_condition:
: For lists, we use the Walrus Operator to assign the element atmy_list[index]
toitem
. We then evaluate some condition using that item.
Example
my_dict = {"a": 1, "b": 2, "c": 3}
if (value := my_dict.get("b")) is not None:
print(f"Value for key 'b' is: {value}")
my_list = [10, 20, 30]
if (item := my_list[1]) > 15:
print(f"Item at index 1 is: {item}")
Explanation
my_dict = {"a": 1, "b": 2, "c": 3}
: Creates a dictionary.if (value := my_dict.get("b")) is not None:
: Uses the Python Walrus Operator to assign the value associated with key “b” tovalue
. It then checks ifvalue
is notNone
.print(f"Value for key 'b' is: {value}")
: Prints the value if the key exists.my_list = [10, 20, 30]
: Creates a list.if (item := my_list[1]) > 15:
: Uses the Walrus Operator to assign the element at index 1 toitem
. It then checks ifitem
is greater than15
.print(f"Item at index 1 is: {item}")
: Prints the item if the condition is true.
Output
Value for key ‘b’ is: 2
Item at index 1 is: 20
List Comprehensions with Python Walrus Operator
Python Walrus Operator can be used within list comprehensions to assign values to variables that you can then use in the comprehension’s expression or condition. This is helpful when you need to perform a calculation once and reuse the result within the comprehension, avoiding redundant computations.
Syntax
[expression for item in iterable if (variable := some_calculation(item)) condition]
Explanation
[expression ... ]
: This is the basic structure of a list comprehension.for item in iterable
: This iterates over theiterable
.if (variable := some_calculation(item))
: The Python Walrus Operator:=
assigns the result ofsome_calculation(item)
tovariable
.condition
: Thecondition
can then use thevariable
.expression
: Theexpression
at the beginning can also use thevariable
.
Example
numbers = [1, 2, 3, 4, 5]
filtered_numbers = [
y for x in numbers
if (y := x * 2) > 6
]
print(filtered_numbers)
Explanation
numbers = [1, 2, 3, 4, 5]
: Creates a list of numbers.filtered_numbers = [ ... ]
: Initializes a list comprehension to create a new list calledfiltered_numbers
.y for x in numbers
: Iterates through thenumbers
list, assigning each element tox
.if (y := x * 2) > 6
:- The Python Walrus Operator
:=
assigns the value ofx * 2
toy
. - Then, it checks if
y
is greater than6
.
- The Python Walrus Operator
- If the condition is true,
y
(which isx * 2
) is added to thefiltered_numbers
list. print(filtered_numbers)
: Prints the new list, which contains only the doubled values greater than 6:[8, 10]
.
Output
[8, 10]
While Loops with Python Walrus Operator
Python Walrus Operator can be particularly useful in while loops where you need to repeatedly check a condition based on a value that’s updated within the loop. Instead of assigning the value in a separate line before the loop or at the end of the loop body, you can use the Walrus Operator to do the assignment directly within the while
condition.
Syntax
while (variable := some_function()) condition:
# Do something with variable
# …
Explanation of the Syntax:
while (variable := some_function()) condition:
: The Python Walrus Operator:=
assigns the result ofsome_function()
tovariable
within thewhile
loop’s condition.- The
condition
is then evaluated using the newly assigned value ofvariable
. - The loop continues as long as the
condition
is true.
Example
# Simulate reading lines from a file, stopping when an empty line is encountered
def get_next_line():
"""Simulates reading a line from a file."""
lines = ["line 1", "line 2", "", "line 4"]
for line in lines:
yield line
my_line = get_next_line()
while (line := next(my_line, '')) != '':
print(f"Processing: {line}")
Explanation
def get_next_line():
: Defines a generator function to simulate reading lines from a file.lines = ["line 1", "line 2", "", "line 4"]
: A list of strings to simulate lines in a file.for line in lines:
: Iterates through thelines
.yield line
: Yields eachline
one at a time, making this a generator.my_line = get_next_line()
: It calls the generator functionget_next_line()
. It will return a generator object.while (line := next(my_line, '')) != '':
:- The Python Walrus Operator
:=
assigns the next value frommy_line
(which yields lines from generator functionget_next_line
) toline
. If there are no more values, it assigns an empty string ” (provided as the default value tonext
). - The loop continues as long as
line
is not an empty string.
- The Python Walrus Operator
print(f"Processing: {line}")
: Prints the current line. The loop will process “line 1”, “line 2”, and then stop because the next line is an empty string which makes the while loop condition false.
Output
Processing: line 1
Processing: line 2
Conclusion
Python Walrus Operator ( :=
) allows you to perform assignments within expressions, reducing the need for extra lines of code and improving readability in certain situations. However, it’s important to be mindful of pitfalls like reduced clarity when overused and understand its precedence and scoping rules. If you are a beginner programmer, do not overuse it. If you master it over time, you will know where to use it to make code more efficient.