The Walrus Operator

Published by Brayan K

The walrus operator := is an assignment expression that assigns a value to a variable and returns that value at the same time, letting you capture a result inside a larger expression.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Keep a result where you also need to test it

Use an assignment expression when a computation is needed both for a decision and for the work that follows. The name on the left receives the value on the right, and the surrounding expression can use that same value. In this example, the count is calculated once, tested and then displayed.

tasks = ["read", "draft", "review"]
if (count := len(tasks)) >= 3:
    print("batch:", count)
print("saved count:", count)

# ✅ Expected output:
# batch: 3
# saved count: 3

A normal assignment on a separate line would also be correct and is often clearer. The useful question is whether capturing the value here makes the decision easier to read. The walrus does not make len() faster or create a special kind of variable. It is an expression form of assignment, not an equality comparison.

Ordinary assignments and comparisons are covered in Operators and Expressions in Python. Loop control remains the subject of Loops: Repeating Code in Python; this lesson focuses on where a captured value comes from and when it is available.

The parentheses decide what gets saved

Assignment expressions bind less tightly than comparisons. Without parentheses around the intended right-hand value, it is easy to save the comparison result instead of the count. Both programs below run, so a syntax check alone will not catch the mistake.

tasks = ["read", "draft", "review"]
if count := len(tasks) >= 3:
    print(count)
print(type(count).__name__)

# ✅ Expected output:
# True
# bool

Put the parentheses around the assignment expression before comparing it. Now count refers to the number of tasks, and the comparison is used only to choose the branch.

tasks = ["read", "draft", "review"]
if (count := len(tasks)) >= 3:
    print(count)
print(type(count).__name__)

# ✅ Expected output:
# 3
# int

Capture in the filter before using the result

A comprehension tests its filter before evaluating its result expression for that item. That gives you a place to compute and retain a cleaned value once, discard empty values, and use the retained value as the result. The helper prints a trace so you can see each call without relying on timings.

def clean(text):
    print("cleaning:", repr(text))
    return text.strip()

raw_labels = [" Ada ", "   ", " Lin ", ""]
labels = [label for raw in raw_labels if (label := clean(raw))]
print(labels)
print("last captured:", repr(label))

# ✅ Expected output:
# cleaning: ' Ada '
# cleaning: '   '
# cleaning: ' Lin '
# cleaning: ''
# ['Ada', 'Lin']
# last captured: ''

The final raw label is empty and is filtered out, but the assignment still happened while testing it. The captured label therefore contains the final empty string, not the last label kept in the result. Unlike the comprehension iteration variable, a walrus target in this situation binds in the containing scope.

The ordering of the for, filter and result parts is taught in List, Dict & Set Comprehensions. Reusing the captured value here removes a second call to clean(); it does not imply that every shorter comprehension is easier to maintain.

A loop can stop at the wrong kind of false value

An assignment in a while condition takes place every time the condition is evaluated. It does not decide what your end marker means. The first loop below accidentally treats a real zero as the end of the stream, leaving the final number unprocessed:

values = iter([2, 0, 3])
while value := next(values, None):
    print(value)
print("stopped at:", value)

# ✅ Expected output:
# 2
# stopped at: 0

If None is the end marker and zero is data, compare explicitly with None. next() advances this iterator, so each condition examines a fresh value. A walrus loop still needs something that makes progress; repeatedly assigning the same truthy value would not stop by itself.

values = iter([2, 0, 3])
while (value := next(values, None)) is not None:
    print(value)
print("end reached:", value is None)

# ✅ Expected output:
# 2
# 0
# 3
# end reached: True

None & NoneType explains the distinction between a sentinel and valid falsy data. This loop assumes None is not one of the readings you need to process.

Read each byte chunk once

A binary file read returns empty bytes at the end. Here that false value really is the stop marker. Capture each read in the condition and process that same chunk in the body; reading again in the body would skip the chunk you just tested.

from io import BytesIO

with BytesIO(b"ABCDEFG") as stream:
    total = 0
    while chunk := stream.read(3):
        print(chunk)
        total += len(chunk)
    print("bytes:", total)
    print("end marker:", repr(chunk))

# ✅ Expected output:
# b'ABC'
# b'DEF'
# b'G'
# bytes: 7
# end marker: b''

The final nonempty chunk can be shorter than the requested size and still needs processing. The next read saves empty bytes to chunk and ends the loop. With a regular blocking file opened in binary mode, the same pattern can use while chunk := f.read(65_536):; the small size above just makes the boundaries visible.

Working with Files, Streams & Large Datasets owns file modes, buffering and stream lifetimes. This pattern relies on that stream's end marker; it is not a rule for every data source that might return a false value.

An expression that never runs cannot assign its name

A short-circuited operand can skip an assignment expression entirely. Defining a name somewhere in the source is not enough; execution must reach that assignment before the name can be read. Here the false flag prevents the right-hand operand from running:

enabled = False
if enabled and (saved_count := 3):
    print("ready")
print(saved_count)

# ✅ Expected error:
# NameError: name 'saved_count' is not defined

If later code needs to inspect the name in either case, initialise it first with a value whose meaning is clear. Alternatively, keep all uses inside the branch that actually made the assignment.

saved_count = None
enabled = False
if enabled and (saved_count := 3):
    print("ready")
print(saved_count is None)

# ✅ Expected output:
# True

Parentheses do not make every assignment target legal

A walrus target must be a name. It cannot be a list item, an attribute or an unpacking pattern. Adding parentheses to a subscript assignment does not change that restriction:

items = [0]
(items[0] := 7)

# ✅ Expected error:
# SyntaxError: cannot use assignment expressions with subscript

Use a normal assignment statement to update the item, then read it if needed. In expression statements such as a standalone capture, parentheses are required, but they are a syntax requirement rather than permission to use any target.

items = [0]
items[0] = 7
print(items[0])
(saved := 7)
print(saved)

# ✅ Expected output:
# 7
# 7

Keep cleaned names and report their count

Fill the first blank with the expression that cleans raw text, and the second with the minimum number of names needed for a group. Capture the cleaned value in the filter so the result expression can reuse it. A group needs at least two nonempty names.

raw_names = [" Ada ", "", " Lin "]
names = [name for raw in raw_names if (name := ___)]
if (count := len(names)) >= ___:
    print(names)
    print("group size:", count)

# 👉 replace ___ with raw.strip()
# 👉 replace ___ with 2

# ✅ Expected output:
# ['Ada', 'Lin']
# group size: 2

Summarise a stream that includes zero

Process the numbers in the solution until the first None. Report how many numbers were processed and their total. Zero must count as a processed number, and the value after the None must not be consumed as part of the report. Initialise both accumulators before the loop so an immediately ended stream would also be safe.

values = iter([3, 0, 2, None, 9])
count = 0
total = 0
while (value := next(values, None)) is not None:
    count += 1
    total += value
print("count:", count)
print("total:", total)

# ✅ Expected output:
# count: 3
# total: 5

Practice quiz

What does this program print? print((count := len("abc")), count)

  • True True
  • 3 3
  • None 3
  • 3 None

Answer: 3 3. The expression saves and evaluates to the same count.

What does this program print? count = (size := len("abc") > 2) print(size, type(size).__name__)

  • 3 int
  • False bool
  • True int
  • True bool

Answer: True bool. The comparison binds more tightly, so size receives its Boolean result.

What does this program print? print((size := len("abc")) > 2) print(size)

  • True 3
  • True True
  • 3 True
  • False 3

Answer: True 3. The parentheses capture the length before comparing it.

What does this program print? labels = [name for raw in [" A ", ""] if (name := raw.strip())] print(labels, repr(name))

  • ['A'] 'A'
  • [] ''
  • ['A'] ''
  • A NameError

Answer: ['A'] ''. The final filter assigns an empty string even though that item is not kept.

What does this program print? saved = None flag = False result = flag and (saved := 3) print(saved, result)

  • 3 False
  • None False
  • 3 True
  • None True

Answer: None False. The false flag short-circuits before the assignment.

What does this program print? values = iter([0, 2]) print((value := next(values, None)) is not None) print(value)

  • False 0
  • True 2
  • False None
  • True 0

Answer: True 0. Zero is a real value and is not the None sentinel.

Which target is permitted in an assignment expression?

  • A plain name such as count
  • A list item such as items[0]
  • An attribute such as item.count
  • An unpacking pair such as left, right

Answer: A plain name such as count. The assignment-expression target must be an identifier.

What does this program print? from io import BytesIO stream = BytesIO(b"abcde") sizes = [] while chunk := stream.read(2): sizes.append(len(chunk)) print(sizes, chunk)

  • [2, 2] b'e'
  • [2, 2, 1, 0] b''
  • [2, 2, 1] b''
  • [2, 2, 1] None

Answer: [2, 2, 1] b''. The short final chunk is processed. The following read assigns empty bytes, whose false truth value ends the loop.

Continue this course

Related lessons