Learning

Walrus Operator (:=)

Walrus Operator (:=)

Basic Syntax

python
# Without walrus name = input('Name: ') if name: print(f'Hello, {name}') # With walrus if (name := input('Name: ')): print(f'Hello, {name}')

While Loop Patterns

python
# Without walrus — duplicated input() call while True: line = input('> ') if line == 'quit': break print(f'You said: {line}') # With walrus — cleaner while (line := input('> ')) != 'quit': print(f'You said: {line}')

List Comprehension Reuse

python
import re text = 'foo123bar456baz789' # Without walrus — calls int() twice! big = [int(m) for m in re.findall(r'\d+', text) if int(m) > 200] # With walrus — int() called once big = [n for m in re.findall(r'\d+', text) if (n := int(m)) > 200] # [456, 789]

if-else Chains

python
import json # Without walrus — parse twice or use temp var data = None raw = get_response() if raw: data = json.loads(raw) if data and 'name' in data: print(data['name']) # With walrus if (raw := get_response()) and (data := json.loads(raw)) and 'name' in data: print(data['name'])

Processing Streams

python
# Filter and transform in one pass def get_values(): yield 5 yield 15 yield 3 yield 25 yield 8 # Without walrus — need helper function or two passes result = [processed for v in get_values() if (processed := v * 2) > 10] # [30, 50, 16]

Readability Considerations

python
# GOOD: Reduces duplication if (match := pattern.search(text)): print(match.group()) # BAD: Overly complex, hard to read if (a := foo()) and (b := bar(a)) and (c := baz(b)): process(c) # BETTER: Split into clear steps a = foo() if not a: return b = bar(a) if not b: return c = baz(b) if c: process(c)
Key Rules
  • •Walrus operator (:=) assigns a value AND returns it in the same expression
  • •Best use case: assigning AND checking in a single expression to avoid duplication
  • •In comprehensions, walrus avoids calling the same function/expression twice
  • •The walrus expression MUST be in parentheses when used in if/while conditions
  • •Don't chain walrus operators — it hurts readability more than it helps
  • •Walrus creates a REGULAR variable, accessible outside the comprehension too
Your Task

Create a function `process_data(data)` that: 1) Uses walrus in a while loop to process user input until 'done'. 2) Uses walrus in a list comprehension to filter and transform numbers (double them, keep only > 10). 3) Uses walrus in an if chain to check if a string matches a pattern and extract the match. 4) Uses walrus to find the first even number in a list and print it, without a separate variable declaration.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should use walrus in while loop condition
Should use walrus in list comprehension
Should use walrus with re.search in if
Should use any() with walrus for first even
Should import re module
Should have parentheses around walrus in conditions