Skip to content

Walrus Operator

In one line

:= (walrus operator) assigns a value to a variable AND returns it in the same expression — saves a line.

In simple words

The walrus operator := (named for its resemblance to walrus eyes and tusks) assigns a value to a variable and returns that value in the same expression. Introduced in Python 3.8.

It's useful for:

  1. Avoiding duplicate calls — assign once, use in condition and body
  2. List comprehensions with conditions — compute and filter in one pass
  3. While loops — assign and test in one line

if (n := len(data)) > 10: print(n) — assigns len(data) to n, then tests n > 10, and n is available in the body.

Example

python
# Without walrus — calls len() twice
# data = get_data()
# if len(data) > 10:
#     print(f"Got {len(data)} items")

# With walrus — calls once
data = [1, 2, 3, 4, 5]
if (n := len(data)) > 3:
    print(f"Got {n} items")  # n is available here

# In list comprehension — compute and filter
nums = [1, 2, 3, 4, 5, 6]
# Without: compute y twice for each x
# With: compute once
results = [y for x in nums if (y := x ** 2) > 10]
print(results)  # [16, 25, 36]

# While loop pattern
chunks = []
while (chunk := data[:2]):
    chunks.append(chunk)
    data = data[2:]

:= assigns and returns in one expression. Avoids duplicate computation and makes code more concise in conditions and comprehensions.

Common confusions

  • Confused with: regular assignment

    The difference: Regular assignment (=) is a statement — it cannot be used inside expressions (if, while, comprehension conditions). The walrus operator (:=) is an expression — it assigns AND returns a value, usable anywhere an expression is valid.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary