The Walrus Operator :=

Assign inside an expression to avoid repeating work — used well, it reads beautifully.

The walrus operator := (named for its := eyes-and-tusks look) assigns a value and returns it, all inside a larger expression. It was added in Python 3.8 to kill a common repetition.

The problem it solves

You often compute something, test it, then use it again — writing the computation twice or adding an extra line:

# Without walrus: value computed, then re-used
data = get_data()
if data:
    process(data)

# With walrus: compute, test, and bind in one breath
if (data := get_data()):
    process(data)

Where it earns its keep

  • In while loops reading until a sentinel: while (line := f.readline()):.
  • Inside comprehensions to avoid calling an expensive function twice.
  • In if/elif chains where you need the tested value in the body.

Use it sparingly. When it removes a genuine repetition it is a joy; when it just crams two ideas onto one line, a plain assignment is kinder to the next reader.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A while loop reads and processes chunks from a file until the read returns an empty bytes object.
  • A list comprehension uses := to filter by a computed value and include that value in the output list.
  • A regex search assigns the match object with := inside an if statement to avoid calling re.search twice.

More examples

Walrus in a while loop

Assigns the read() result to 'chunk' and tests it in the same expression, replacing the read-twice pattern.

Example · python
import io
buf = io.BytesIO(b'hello world')
while chunk := buf.read(5):
    print(chunk)

# Output:
# b'hello'
# b' worl'
# b'd'

Walrus in a list comprehension

Computes y := x*2 once inside the comprehension, uses it in the filter and includes it in the output.

Example · python
data = [1, 4, 9, 16, 25]
results = [y for x in data if (y := x * 2) > 10]
print(results)   # [18, 32, 50]

Walrus with regex match

Uses := to assign the match object in the if-condition, avoiding a separate assignment line.

Example · python
import re

lines = ['Order #1042: shipped', 'Inquiry: no order', 'Order #2201: pending']
for line in lines:
    if m := re.search(r'#(\d+)', line):
        print('Order number:', m.group(1))

# Output:
# Order number: 1042
# Order number: 2201

Discussion

  • Be the first to comment on this lesson.