Python Walrus operator

Good examples of the Python walrus operator.

From: https://www.reddit.com/r/Python/comments/1rw18i5/comment/oaxdl2e/

# perfect for re.match
if has_whatever := re.match(stuff)
    a, b = has_whatever.groups()

###

only call other_function if res is some value
if (result := some_fun()) in ("a", "b"):
    other_function(res)

###

# conditional based on the result of res
if func(res := gfunc()):
    # use res safely


###

while line := fp.readline():
    ...

###

if bad := [r for r in records if r.bad()]:
    raise ValueError('Bad records: ' + ', '.join(b.name for b in bad))

From PEP 572: The Walrus Operator [Pycon 2019]:

# Instead of:

y = f(x)
foo = []
if y:
    foo = [y, y**2, y**3]

# use

foo = [y := f(x), y**2, y**3]

###

# Instead of

results = []
for x in data:
    r = f(x)
    if r :
        results.append(result)

# use

results [
    y for x in data
    if (y := f(x))
]

SamatsWiki: Python/Walrus (last edited 2026-03-20 17:42:36 by SamatJain)