pythonbeginner

Walrus Operator := Patterns

Use the walrus operator (:=) for concise assignment-in-expression patterns.

python
# Filter and transform in one pass
data = [1, -2, 3, -4, 5, -6, 7]
positive_doubles = [
    doubled
    for x in data
    if (doubled := x * 2) > 0
]
print(positive_doubles)  # [2, 6, 10, 14]

# Read until EOF
import io
buffer = io.StringIO("line1\nline2\nline3\n")
while (line := buffer.readline()):
    print(line.strip())

# Avoid repeated computation
import re
text = "Contact: alice@example.com"
if (match := re.search(r'[\w.]+@[\w.]+', text)):
    print(f"Found email: {match.group()}")

# Complex list comprehension filtering
values = ["10", "abc", "20", "def", "30"]
numbers = [
    n
    for v in values
    if (n := _try_int(v)) is not None
]

def _try_int(s):
    try: return int(s)
    except ValueError: return None

Use Cases

  • Concise filtering
  • While-loop reads
  • Regex matches

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.