CodeNebula
Python🔧Core Languagebeginner

Walrus Operator `:=` (Python 3.8+)

Python · Core Language · Run with python3

Explanation

The walrus operator (`:=`, PEP 572) assigns a value to a variable and returns it in a single expression. It's most useful inside `while` conditions (avoiding a duplicate read), comprehension conditions (capturing an intermediate computed value), and `if` statements (avoiding re-computation). It makes imperative "compute, check, use" patterns more concise without sacrificing readability when used judiciously.

Real-World Scenario

Reading a socket in a loop: `while data := sock.recv(1024):` reads data and checks for EOF (empty bytes) in one expression. Previously you needed `data = sock.recv(1024); while data:` — two lines with the read duplicated before the loop. ```python import re # Walrus in a while loop — read chunks until EOF def count_chars(text: str, chunk_size: int = 4) -> int: total = 0 pos = 0 while chunk := text[pos:pos + chunk_size]: total += len(chunk) pos += chunk_size return total print(count_chars("Hello, World!")) # 13 # Walrus in comprehension — avoid recomputing expensive fn data = [1, -2, 3, -4, 5] results = [y for x in data if (y := x * x) > 4] print(results) # [4, 9, 16, 25] — wait, condition is y > 4 # => [9, 16, 25] # Walrus in regex match text = "Order #12345 placed" if m := re.search(r"#(\d+)", text): print(f"Order ID: {m.group(1)}") # Order ID: 12345 ```

Quick Snippet

snippet.py
import re

# Walrus in a while loop — read chunks until EOF
def count_chars(text: str, chunk_size: int = 4) -> int:
    total = 0
    pos = 0
    while chunk := text[pos:pos + chunk_size]:
        total += len(chunk)
        pos += chunk_size
    return total

print(count_chars("Hello, World!"))  # 13

# Walrus in comprehension — avoid recomputing expensive fn
data = [1, -2, 3, -4, 5]
results = [y for x in data if (y := x * x) > 4]
print(results)  # [4, 9, 16, 25] — wait, condition is y > 4
# => [9, 16, 25]

# Walrus in regex match
text = "Order #12345 placed"
if m := re.search(r"#(\d+)", text):
    print(f"Order ID: {m.group(1)}")  # Order ID: 12345

Full Example

walrus_operator.py
# Compile: python3 walrus_operator.py
# Output:
# 13
# [9, 16, 25]
# Order ID: 12345

import re

def count_chars(text: str, chunk_size: int = 4) -> int:
    total = 0
    pos = 0
    while chunk := text[pos:pos + chunk_size]:
        total += len(chunk)
        pos += chunk_size
    return total

print(count_chars("Hello, World!"))

# Walrus in comprehension condition
data = [1, -2, 3, -4, 5]
results = [y for x in data if (y := x * x) > 4]
print(results)

# Walrus in regex match
text = "Order #12345 placed"
if m := re.search(r"#(\d+)", text):
    print(f"Order ID: {m.group(1)}")

# Without walrus (old style)
match = re.search(r"#(\d+)", text)
if match:
    print(f"Order ID: {match.group(1)}")  # same result
Run command
python3 walrus_operator.py