Python Snippet

Walrus Operator Patterns

Difficulty: Medium

The walrus operator `:=` (Python 3.8+) lets you assign and use a value in the same expression. It is the right tool for caching expensive expressions inside comprehensions, reading until a sentinel, and tightening the common 'compute, then check' pattern. This snippet covers the loop-with-sentinel use, the comprehension-cache use, and the regex-match conditional that is the most-cited textbook example.

Code Snippets
/

Walrus Operator Patterns

Walrus Operator Patterns

The walrus operator `:=` (Python 3.8+) lets you assign and use a value in the same expression. It is the right tool for caching expensive expressions inside comprehensions, reading until a sentinel, and tightening the common 'compute, then check' pattern. This snippet covers the loop-with-sentinel use, the comprehension-cache use, and the regex-match conditional that is the most-cited textbook example.

Python
Medium
3 snippets
py-walrus-operator
code-template
cheat-sheet
py-standard-library

605 views

11

The walrus operator collapses the classic 'read once, check, read again' pattern into a single line: while (chunk := stream.readline()):. The expression evaluates to the assigned value, so an empty string (the EOF sentinel from readline) makes the loop exit naturally. This is the cleanest pattern for streams, generators with sentinels, and any iterator-like API that does not implement the iterator protocol. The parentheses around the walrus expression are required when it is the entire condition.