Fundamentals 5 min read

Understanding the Walrus Operator (:=) in Python 3.8

Python 3.8 introduced the walrus operator (:=), a concise assignment expression that allows in-line variable assignment within expressions, and this article explains its purpose, benefits, and provides ten practical code examples illustrating its use in loops, comprehensions, conditionals, and function calls.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding the Walrus Operator (:=) in Python 3.8

Python 3.8 added a new operator called the walrus operator (:=). Named for its resemblance to a walrus’s mouth and whiskers, it enables assignment within an expression, making code more elegant and concise.

What is the walrus operator? In Python, := is an assignment expression that lets you assign a value anywhere an expression is allowed, eliminating the need for a separate assignment statement. This is especially useful in loops, conditionals, and function calls, reducing line count and improving readability.

Code examples

Example 1: Using it in a while loop

lines = ["Hello", "World", "Python"]
while (line := lines.pop()) != "Python":
    print(line)
print("Found Python!")

Example 2: Initialising a counter in a for loop

for (i := 0) in range(10):
    print(i)

Example 3: Using it in a list comprehension

numbers = [1, 2, 3, 4, 5]
squares = [(n := n**2) for n in numbers]
print(squares)

Example 4: Using it in an if condition

if (value := 42) > 10:
    print(f"Value is greater than 10: {value}")

Example 5: Checking before a function call

def process_data(data):
    print(f"Processing data: {data}")

data = [1, 2, 3]
if (d := len(data)) > 0:
    process_data(d)

Example 6: Combining with logical operators

if (file := open('example.txt')) and (content := file.read()):
    print(content)
finally:
    file.close()

Example 7: Using it in a dictionary comprehension

data = {'a': 1, 'b': 2}
keys = ['a', 'b', 'c']
mapped_data = {k: data[k] if (k := k) in data else None for k in keys}
print(mapped_data)

Example 8: Filtering a list

words = ['Python', 'is', 'awesome']
long_words = [word for word in words if (len(word) := len(word)) > 5]
print(long_words)

Example 9: Using it in a generator expression

gen = ((i := i+1) for i in range(5))
for num in gen:
    print(num)

Example 10: Unpacking a tuple

t = (1, 2, 3)
(a := t[0], b := t[1], c := t[2])
print(f"a={a}, b={b}, c={c}")

It is recommended to practice these examples and observe their output to fully grasp the operator’s behavior.

Conclusion The walrus operator := is a powerful feature introduced in Python 3.8 that can make code shorter and clearer. Use it judiciously, as excessive nesting may hurt readability, but mastering it will enhance your Python programming experience.

code examplesassignment-expressionPython 3.8walrus-operator
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.