- What is the walrus operator — the assignment expression operator (:=)
- Why use it — write shorter, cleaner code
- Basic syntax — how to use :=
- While loops — assign and check in one step
- If statements — assign and test conditions
- List comprehensions — more efficient comprehensions
What is the Walrus Operator?
The walrus operator (:=) is a special operator introduced in Python 3.8. It's called the "walrus operator" because it looks like a walrus with two tusks and eyes.
The walrus operator does two things at once: it assigns a value to a variable AND returns that value so you can use it immediately. This lets you write shorter, cleaner code.
Think of it like a vending machine that gives you a receipt. You put in money, get your snack, and also get a receipt showing what you bought. The walrus operator does the same thing — it does the assignment AND gives you the value right away.
💡 Key concept: The walrus operator lets you assign a value and use it in the same expression. It's written as := and is read as "assigns and returns".
Why Use the Walrus Operator?
The Benefits of :=
The walrus operator helps you write cleaner, more efficient code. Let's see how.
# Why Use the Walrus Operator?
print("=" * 50)
print("WHY USE THE WALRUS OPERATOR?")
print("=" * 50)
# ============================================================
# WITHOUT WALRUS OPERATOR — Two Steps
# ============================================================
print("\n1. WITHOUT WALRUS OPERATOR")
def get_user_input():
return input(" Enter something: ")
# Old way: assign, then check
data = get_user_input()
if data:
print(f" You entered: {data}")
else:
print(" Nothing entered")
# Problems: two separate statements for a simple check
# Can't use the value directly in the condition
# ============================================================
# WITH WALRUS OPERATOR — One Step
# ============================================================
print("\n2. WITH WALRUS OPERATOR")
# New way: assign and check in one line
if (data := get_user_input()):
print(f" You entered: {data}")
else:
print(" Nothing entered")
print(" One line does assignment AND condition check")
# ============================================================
# BENEFITS
# ============================================================
print("\n" + "-" * 30)
print("BENEFITS OF WALRUS OPERATOR")
print("-" * 30)
print("""
- Cleaner code: less repetition
- More readable: assign and use in one place
- More efficient: no redundant calls
- Saves lines of code
- Makes conditions clearer
- Great for while loops that need a sentinel
""")
# ============================================================
# AVOIDING REDUNDANT CALLS
# ============================================================
print("\n3. AVOIDING REDUNDANT CALLS")
import re
# Without walrus (calls function twice or uses temporary variable)
text = "Hello123World456"
# Old way with temporary variable
numbers = re.findall(r'\d+', text)
if numbers:
print(f" Found: {numbers}")
# With walrus (one call, immediate use)
if numbers := re.findall(r'\d+', text):
print(f" Found: {numbers}")
print(" No temporary variable needed")
Benefits of walrus operator:
- Cleaner code — less repetition
- More readable — assign and use in one place
- More efficient — no redundant function calls
- Saves lines — shorter code
- Better conditions — clearer intent
Quick Check: What does the walrus operator do? (Answer: It assigns a value to a variable and returns that value in the same expression)
Basic Syntax
How to Use :=
The syntax is simple: variable := expression assigns the expression to the variable and returns the value.
# Basic Walrus Operator Syntax
print("=" * 50)
print("BASIC SYNTAX")
print("=" * 50)
# ============================================================
# SIMPLE ASSIGNMENT AND USE
# ============================================================
print("\n1. SIMPLE ASSIGNMENT")
# Without walrus
x = 10
print(f" x = 10, x = {x}")
# With walrus (assign and use in same expression)
print(f" (y := 20) -> y = 20")
print(f" y = {y}") # y is now 20
# The walrus operator returns the value
result = (z := 30)
print(f" (z := 30) returns: {result}")
print(f" z = {z}")
# ============================================================
# USING IN EXPRESSIONS
# ============================================================
print("\n2. USING IN EXPRESSIONS")
# Without walrus
a = 5
b = a + 3
print(f" a = 5, b = a + 3 = {b}")
# With walrus
b = (a := 5) + 3
print(f" (a := 5) + 3 = {b}, a = {a}")
# Multiple uses
x = (y := 10) * (z := 2)
print(f" (y := 10) * (z := 2) = {x}")
print(f" y = {y}, z = {z}")
# ============================================================
# WALRUS IN PRINT STATEMENTS
# ============================================================
print("\n3. WALRUS IN PRINT STATEMENTS")
# You can assign and print at the same time
print(f" (value := 100) -> {value := 100}")
print(f" value = {value}")
# ============================================================
# WALRUS WITH MATH
# ============================================================
print("\n4. WALRUS WITH MATH")
# Assign and compute
area = (side := 5) ** 2
print(f" side = {side}, area = {area}")
# Assign and use in formula
double = (num := 7) * 2
print(f" num = {num}, double = {double}")
# ============================================================
# IMPORTANT: PARENTHESES
# ============================================================
print("\n5. IMPORTANT: PARENTHESES")
# Without parentheses (works in some cases)
x = 42
print(f" x = 42")
# With parentheses (recommended for clarity)
if (y := 100) > 50:
print(f" y = {y} is greater than 50")
# Without parentheses can cause issues
# if result := len("hello") > 3: # This works but is confusing
# print(f" length is {result}")
print(" Use parentheses for clarity: (variable := expression)")
# ============================================================
# WALRUS VS REGULAR ASSIGNMENT
# ============================================================
print("\n6. WALRUS VS REGULAR ASSIGNMENT")
print("""
Regular assignment ( = ):
- Assigns a value to a variable
- Does NOT return the value
- Used in statements, not expressions
Walrus assignment ( := ):
- Assigns a value to a variable
- RETURNS the value
- Can be used in expressions
- Requires parentheses for clarity
""")
print(" Example:")
print(" if value := get_data(): # Works")
print(" if value = get_data(): # Syntax Error")
Basic syntax key points:
- variable := expression — assigns and returns
- Use parentheses —
(name := value)for clarity - Returns value — the expression's result
- Not an operator — it's an assignment expression
- Cannot be used alone — must be inside an expression
Quick Check: What's the difference between = and :=? (Answer: = assigns only, := assigns AND returns the value)
Using in While Loops
Better While Loops with :=
The walrus operator is especially useful in while loops when you need to get a value, check it, and use it.
# Walrus Operator in While Loops
print("=" * 50)
print("WALRUS IN WHILE LOOPS")
print("=" * 50)
import re
# ============================================================
# USER INPUT LOOP
# ============================================================
print("\n1. USER INPUT LOOP")
# Without walrus (requires break)
print(" Without walrus:")
while True:
data = input(" Enter something (or 'quit' to exit): ")
if data == "quit":
break
print(f" You entered: {data}")
# This is better - with walrus
print("\n With walrus (cleaner):")
# while (data := input(" Enter something (or 'quit' to exit): ")) != "quit":
# print(f" You entered: {data}")
print(" One line does: get input, check condition, and loop")
# ============================================================
# READING FROM A FILE
# ============================================================
print("\n2. READING FROM A FILE")
# Without walrus
print(" Without walrus:")
with open("sample.txt", "w") as f:
f.write("Line 1\nLine 2\nLine 3")
with open("sample.txt", "r") as file:
while True:
line = file.readline()
if not line:
break
print(f" {line.strip()}")
# With walrus (cleaner)
print("\n With walrus:")
with open("sample.txt", "r") as file:
while (line := file.readline()):
print(f" {line.strip()}")
print(" Cleaner: no separate break condition")
# ============================================================
# PROCESSING DATA STREAMS
# ============================================================
print("\n3. PROCESSING DATA STREAMS")
import random
def get_next_data():
"""Simulate getting data from a stream"""
if random.random() < 0.1: # 10% chance of no data
return None
return random.randint(1, 100)
print(" Processing data stream:")
count = 0
while (data := get_next_data()) is not None:
count += 1
print(f" Data {count}: {data}")
if count >= 8: # Limit for demo
break
print(" Data processed")
# ============================================================
# PARSING TEXT
# ============================================================
print("\n4. PARSING TEXT")
text = "Hello 123 World 456 Python 789"
# Find all numbers using regex
pattern = re.compile(r'\d+')
# Without walrus
print(" Without walrus:")
matches = pattern.findall(text)
for match in matches:
print(f" {match}")
# With walrus
print("\n With walrus:")
while (match := pattern.search(text)):
print(f" {match.group()}")
text = text[match.end():]
# ============================================================
# SUMMARY
# ============================================================
print("\n" + "-" * 30)
print("WHILE LOOP PATTERNS")
print("-" * 30)
print("""
Without walrus:
while True:
line = file.readline()
if not line:
break
process(line)
With walrus:
while (line := file.readline()):
process(line)
- Cleaner code
- No separate break
- Less repetition
- More readable
""")
While loops with walrus key points:
- Read lines —
while (line := file.readline()): - User input —
while (data := input()) != "quit": - Stream data —
while (data := get_data()) is not None: - No break needed — condition handles the loop
- Cleaner code — assign and check in one line
Quick Check: How would you use the walrus operator to read lines from a file? (Answer: while (line := file.readline()):)
Using in If Statements
Better Conditions with :=
The walrus operator lets you assign and check a value in an if statement.
# Walrus Operator in If Statements
print("=" * 50)
print("WALRUS IN IF STATEMENTS")
print("=" * 50)
import re
# ============================================================
# SIMPLE IF CHECK
# ============================================================
print("\n1. SIMPLE IF CHECK")
# Without walrus
data = input(" Enter a number (or press Enter for none): ")
if data:
print(f" You entered: {data}")
else:
print(" Nothing entered")
# With walrus (cleaner)
if (data := input(" Enter a number (or press Enter for none): ")):
print(f" You entered: {data}")
else:
print(" Nothing entered")
print(" No temporary variable needed")
# ============================================================
# REGULAR EXPRESSION MATCHING
# ============================================================
print("\n2. REGULAR EXPRESSION MATCHING")
text = "My email is john@example.com and my phone is 555-1234"
# Without walrus
email_match = re.search(r'\w+@\w+\.\w+', text)
if email_match:
print(f" Email: {email_match.group()}")
# With walrus (one line)
if email_match := re.search(r'\w+@\w+\.\w+', text):
print(f" Email: {email_match.group()}")
print(" No temporary variable needed")
# ============================================================
# CHECKING FUNCTION RESULTS
# ============================================================
print("\n3. CHECKING FUNCTION RESULTS")
import random
def get_data():
"""Simulate getting data"""
return random.choice([None, "data", "more data", "even more data"])
# Without walrus
result = get_data()
if result:
print(f" Got: {result}")
# With walrus
if result := get_data():
print(f" Got: {result}")
# ============================================================
# MULTIPLE CONDITIONS
# ============================================================
print("\n4. MULTIPLE CONDITIONS")
# Without walrus
def validate_email(email):
return '@' in email and '.' in email
email = input(" Enter email: ")
if email and validate_email(email):
print(f" Valid email: {email}")
else:
print(" Invalid email")
# With walrus (cleaner)
if (email := input(" Enter email: ")) and validate_email(email):
print(f" Valid email: {email}")
else:
print(" Invalid email")
# ============================================================
# IF-ELIF CHAINS
# ============================================================
print("\n5. IF-ELIF CHAINS")
def get_priority(data):
"""Get priority from data"""
if data and 'urgent' in data:
return 'high'
elif data and 'normal' in data:
return 'medium'
else:
return 'low'
# Without walrus
text = input(" Enter message: ")
priority = get_priority(text)
if priority == 'high':
print(" High priority!")
elif priority == 'medium':
print(" Medium priority")
else:
print(" Low priority")
# This is simpler without walrus for complex conditions
# ============================================================
# SUMMARY
# ============================================================
print("\n" + "-" * 30)
print("IF STATEMENT PATTERNS")
print("-" * 30)
print("""
Without walrus:
result = function()
if result:
process(result)
With walrus:
if (result := function()):
process(result)
- Fewer lines
- Less repetition
- Cleaner code
- No temporary variable
""")
If statements with walrus key points:
- Check and assign —
if (value := function()): - Regex matching —
if (match := re.search(pattern, text)): - Input validation — assign and validate in one line
- Less repetition — no separate assignment line
- Cleaner conditions — clearer intent
Quick Check: How would you use the walrus operator in an if statement? (Answer: if (variable := expression):)
Using in List Comprehensions
More Efficient Comprehensions
The walrus operator can make list comprehensions more efficient by avoiding duplicate calculations.
# Walrus Operator in List Comprehensions
print("=" * 50)
print("WALRUS IN LIST COMPREHENSIONS")
print("=" * 50)
import math
# ============================================================
# AVOID DUPLICATE CALCULATIONS
# ============================================================
print("\n1. AVOID DUPLICATE CALCULATIONS")
numbers = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Without walrus (calculates sqrt twice)
squares = [math.sqrt(x) for x in numbers if math.sqrt(x) > 5]
print(f" Squares > 5: {[round(n, 2) for n in squares]}")
# With walrus (calculates once)
squares_walrus = [root for x in numbers if (root := math.sqrt(x)) > 5]
print(f" Squares > 5: {[round(n, 2) for n in squares_walrus]}")
print(" Walrus avoids calculating sqrt twice!")
# ============================================================
# FILTERING WITH COMPUTED VALUES
# ============================================================
print("\n2. FILTERING WITH COMPUTED VALUES")
data = [("Alice", 25), ("Bob", 17), ("Charlie", 30), ("Diana", 16)]
# Without walrus
adults = [name for name, age in data if age >= 18]
print(f" Adults: {adults}")
# With walrus (if you need the value)
names_with_age = [(name, age) for name, age in data if (is_adult := age >= 18)]
print(f" All with age: {names_with_age}")
# ============================================================
# COMPLEX CALCULATIONS
# ============================================================
print("\n3. COMPLEX CALCULATIONS")
import random
# Generate random numbers
random.seed(42)
values = [random.randint(1, 100) for _ in range(10)]
print(f" Values: {values}")
# Without walrus (calculates expensive function twice)
def expensive_function(x):
"""Simulate an expensive calculation"""
return x ** 2 + 10 * x + 25
filtered = [x for x in values if expensive_function(x) > 500]
print(f" Filtered (without walrus): {filtered}")
# With walrus (calculates once)
filtered_walrus = [x for x in values if (result := expensive_function(x)) > 500]
print(f" Filtered (with walrus): {filtered_walrus}")
print(" With walrus: expensive calculation done once per item")
# ============================================================
# STRING PROCESSING
# ============================================================
print("\n4. STRING PROCESSING")
words = ["hello", "world", "python", "programming", "is", "fun"]
# Without walrus
long_words = [word for word in words if len(word) > 5]
print(f" Long words: {long_words}")
# With walrus (if you need the length)
long_words_with_len = [(word, length) for word in words if (length := len(word)) > 5]
print(f" Long words with length: {long_words_with_len}")
# ============================================================
# NESTED COMPREHENSIONS
# ============================================================
print("\n5. NESTED COMPREHENSIONS")
# Matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Without walrus
flattened = [num for row in matrix for num in row if num % 2 == 0]
print(f" Even numbers: {flattened}")
# With walrus
even_numbers = [num for row in matrix for num in row if (is_even := num % 2 == 0)]
print(f" Even numbers with flag: {even_numbers}")
# ============================================================
# SUMMARY
# ============================================================
print("\n" + "-" * 30)
print("LIST COMPREHENSION PATTERNS")
print("-" * 30)
print("""
Without walrus:
[calc(x) for x in data if calc(x) > threshold] # calc called twice
With walrus:
[result for x in data if (result := calc(x)) > threshold] # calc called once
Benefits:
- Avoid duplicate calculations
- More efficient
- Can use the result in the expression
- Cleaner code
""")
List comprehensions with walrus key points:
- Avoid duplication — calculate once, use twice
- More efficient — especially for expensive operations
- Use in condition — filter and use the computed value
- Nested comprehensions — works the same way
- Cleaner code — less repetition
Quick Check: When is the walrus operator useful in list comprehensions? (Answer: When you need to use a computed value in both the condition and the result)
Real-World Example
Building a Log Parser
# Real-World Example: Log Parser
import re
import random
from datetime import datetime
print("=" * 60)
print("LOG PARSER WITH WALRUS OPERATOR")
print("=" * 60)
# ============================================================
# GENERATE SAMPLE LOGS
# ============================================================
def generate_logs(count=10):
"""Generate sample log entries"""
levels = ["INFO", "WARNING", "ERROR", "DEBUG"]
messages = [
"User logged in",
"Database connection established",
"API request received",
"File uploaded",
"Cache cleared",
"Memory usage high",
"Request timeout",
"User authentication failed",
"System starting up"
]
logs = []
for i in range(count):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
level = random.choice(levels)
msg = random.choice(messages)
# Add some extra data to some logs
if level == "ERROR":
msg += f" (Code: {random.randint(100, 500)})"
elif level == "WARNING":
msg += f" (Threshold: {random.randint(80, 99)}%)"
logs.append(f"[{timestamp}] {level}: {msg}")
return logs
logs = generate_logs(15)
print("\n1. SAMPLE LOGS")
for log in logs:
print(f" {log}")
# ============================================================
# PARSE LOGS WITH WALRUS OPERATOR
# ============================================================
print("\n2. PARSING LOGS WITH WALRUS")
# Pattern to parse logs
log_pattern = re.compile(r'\[(.*?)\] (\w+): (.*)')
error_pattern = re.compile(r'Code: (\d+)')
warning_pattern = re.compile(r'Threshold: (\d+)%')
print(" Extracting data:")
# Parse logs and extract useful information
parsed_logs = []
for log in logs:
if match := log_pattern.match(log):
timestamp, level, message = match.groups()
# Extract error codes
error_code = None
if level == "ERROR":
if code_match := error_pattern.search(message):
error_code = int(code_match.group(1))
# Extract warning thresholds
threshold = None
if level == "WARNING":
if threshold_match := warning_pattern.search(message):
threshold = int(threshold_match.group(1))
parsed_logs.append({
"timestamp": timestamp,
"level": level,
"message": message,
"error_code": error_code,
"threshold": threshold
})
for log in parsed_logs[:5]:
print(f" {log['timestamp']} - {log['level']}: {log['message'][:30]}...")
# ============================================================
# ANALYZE LOGS
# ============================================================
print("\n3. ANALYZING LOGS")
# Count logs by level
level_counts = {}
for log in parsed_logs:
level = log["level"]
level_counts[level] = level_counts.get(level, 0) + 1
print(" Log counts by level:")
for level, count in level_counts.items():
print(f" {level}: {count}")
# Find errors with codes
print("\n Errors with codes:")
errors_with_codes = [
log for log in parsed_logs
if log["level"] == "ERROR" and (code := log["error_code"]) is not None
]
for log in errors_with_codes:
print(f" Code {log['error_code']}: {log['message'][:40]}...")
# Find warnings above threshold
print("\n High warnings (threshold > 90):")
high_warnings = [
log for log in parsed_logs
if log["level"] == "WARNING" and (thresh := log["threshold"]) and thresh > 90
]
for log in high_warnings:
print(f" Threshold {log['threshold']}%: {log['message'][:40]}...")
# ============================================================
# FILTER LOGS WITH WALRUS
# ============================================================
print("\n4. FILTERING LOGS WITH WALRUS")
# Get all error messages with codes
error_messages = [
f"ERROR {code}: {msg[:30]}"
for log in parsed_logs
if log["level"] == "ERROR" and (code := log["error_code"]) is not None
]
print(" Error messages:")
for msg in error_messages:
print(f" {msg}")
# Get warning thresholds
warning_thresholds = [
thresh
for log in parsed_logs
if log["level"] == "WARNING" and (thresh := log["threshold"]) is not None
]
print(f" Warning thresholds: {warning_thresholds}")
# ============================================================
# SUMMARY
# ============================================================
print("\n" + "=" * 60)
print("KEY TAKEAWAYS:")
print("=" * 60)
print("""
- Walrus operator helps parse logs efficiently
- Assign and check in one line
- Extract data while filtering
- Avoid duplicate pattern matching
- Cleaner, more readable code
- Perfect for parsing text data
""")
Real-world example key points:
- Pattern matching — assign and check regex matches
- Extract codes — parse error codes in one line
- Filter logs — use walrus in comprehensions
- Avoid duplication — no redundant pattern matches
- Cleaner code — less repetition in parsing
Quick Check: How does the walrus operator help with parsing logs? (Answer: It lets you assign pattern matches and check them in one line)
Best Practices
Using the Walrus Operator Effectively
# Best Practices for Walrus Operator
print("=" * 60)
print("BEST PRACTICES FOR WALRUS OPERATOR")
print("=" * 60)
import re
# ============================================================
# 1. USE PARENTHESES FOR CLARITY
# ============================================================
print("\n1. USE PARENTHESES FOR CLARITY")
# Good - clear and readable
if (value := len("hello")) > 3:
print(f" length is {value}")
# Bad - confusing and hard to read
# if value := len("hello") > 3: # This is ambiguous
# print(f" length is {value}")
print(" Always use parentheses with := for clarity")
# ============================================================
# 2. DON'T OVERUSE IT
# ============================================================
print("\n2. DON'T OVERUSE IT")
# Good - use when it makes code cleaner
pattern = re.compile(r'\d+')
text = "Hello 123 World"
if match := pattern.search(text):
print(f" Found: {match.group()}")
# Bad - using it when a simple assignment is clearer
# x = 5
# y = x + 3
# if y > 10: # This is clearer than (y := x + 3) > 10
print(" Use it when it improves readability")
# ============================================================
# 3. USE IN WHILE LOOPS FOR SENTINELS
# ============================================================
print("\n3. USE IN WHILE LOOPS FOR SENTINELS")
# Good - perfect for sentinel loops
def get_data():
return random.choice([None, "data1", "data2", "data3"])
import random
count = 0
while (data := get_data()) is not None:
count += 1
print(f" Got: {data}")
if count >= 5:
break
print(" Perfect for reading data streams")
# ============================================================
# 4. USE IN COMPREHENSIONS FOR EFFICIENCY
# ============================================================
print("\n4. USE IN COMPREHENSIONS FOR EFFICIENCY")
# Good - avoids duplicate calculations
numbers = [2, 3, 4, 5, 6, 7, 8, 9]
def expensive(x):
return x ** 3 + x ** 2 + x
results = [result for x in numbers if (result := expensive(x)) > 100]
print(f" Results > 100: {results}")
# Bad - calculate twice
# results = [expensive(x) for x in numbers if expensive(x) > 100] # Expensive called twice
print(" Use it to avoid duplicate calculations")
# ============================================================
# 5. USE IN IF STATEMENTS FOR ASSIGNMENT
# ============================================================
print("\n5. USE IN IF STATEMENTS FOR ASSIGNMENT")
# Good - assign and check in one step
if (email := input(" Enter email: ")) and '@' in email:
print(f" Valid email: {email}")
else:
print(" Invalid email")
print(" Clean input validation")
# ============================================================
# 6. DON'T USE IN SIMPLE ASSIGNMENTS
# ============================================================
print("\n6. DON'T USE IN SIMPLE ASSIGNMENTS")
# Bad - unnecessary use of walrus
# x := 5 # This works but is not needed
# y = 5 # This is better
# Good - regular assignment for simple cases
x = 5
y = 10
print(f" x = {x}, y = {y}")
# ============================================================
# 7. SUMMARY
# ============================================================
print("\n" + "=" * 60)
print("BEST PRACTICES SUMMARY")
print("=" * 60)
print("""
- Use parentheses for clarity
- Don't overuse it
- Use in while loops for sentinels
- Use in comprehensions for efficiency
- Use in if statements for assignment
- Don't use for simple assignments
- Keep code readable first
""")
Best practices summary:
- Use parentheses — for clarity
- Don't overuse — use when it improves readability
- While loops — perfect for sentinel values
- Comprehensions — avoid duplicate calculations
- If statements — assign and check in one line
- Simple assignments — use = not :=
Quick Check: When should you NOT use the walrus operator? (Answer: For simple assignments where it doesn't improve readability)
Try It Yourself
Experiment with the walrus operator in the editor below.
Note: This editor does not support running code that requires user input.
Please run the program on your system to test input-based code such as input().
WALRUS OPERATOR - PRACTICE
==================================================
1. BASIC USAGE
Length is 11
(num := 42) -> 42
num = 42
2. WHILE LOOP
Getting data:
Data 1: 30
Data 2: 20
Data 3: 40
Data 4: 10
Data 5: 30
3. IF STATEMENT
First number: 123
4. LIST COMPREHENSION
Old way: [36, 49, 64, 81, 100]
Walrus way: [36, 49, 64, 81, 100]
You've Got It!
You now understand the walrus operator (:=) in Python. You know how to use it in while loops, if statements, and list comprehensions.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the walrus operator in Python?
What's the difference between = and :=?
= is the regular assignment operator. It assigns a value but doesn't return it. := is the walrus operator. It assigns AND returns the value, so you can use it in expressions.
When should I use the walrus operator?
Do I need parentheses around the walrus operator?
if (value := get_data()): is clearer than if value := get_data():. Some contexts require parentheses.
Is the walrus operator available in all Python versions?
Can I use the walrus operator in lambda functions?
lambda x: (y := x * 2) + y assigns x*2 to y and uses it in the expression.
Where to Go From Here
Now that you understand the walrus operator in Python, check out these related topics:
Match-Case
Learn about pattern matching in Python.
Learn More →Decorators
Learn about decorators — another advanced Python feature.
Learn More →Generators
Learn about generators and how they work with the walrus operator.
Learn More →