Codectionary / Developer documentation / Python

Assignment expressions (:=)

Bind a result inside an expression when naming it there makes a condition easier to follow.

How it works

The := operator, introduced in Python 3.8, binds a value to a name and also produces that value as the expression result. It can avoid calculating the same result twice.

The assignment target is a simple name, not an attribute or subscription. Parentheses are required in some contexts and can clarify precedence. Ordinary assignment statements remain preferable when a separate step is easier to read.

Limitations and practical choices

Parenthesise the assignment when comparing its result: (count := len(items)) > 3 stores the length, whereas count := len(items) > 3 stores a Boolean.

Use this sparingly. Combining several assignments and conditions into one expression can make debugging harder.

Try it yourself

Read a small sequence until a sentinel is reached, naming each value in the loop condition. Compare it with an explicit while loop and choose the clearer version.

Syntax

if (count := len(items)) > 3:
    print(count)

Examples

Reuse a measured length

Report a long title without measuring it twice.

title = "Python notes"
if (length := len(title)) > 10:
    print("Long title:", length)
  1. len returns twelve. The assignment expression binds that integer to length, then the comparison tests it against ten.
  2. The body can reuse length directly. Parentheses make it clear that the integer, rather than the comparison result, is stored.
  3. This is useful when a calculated value is needed both for a decision and its diagnostic message.
  4. Expected output: Long title: 12

Read chunks until empty

Use a bounded in-memory stream to illustrate repeated reads.

from io import StringIO
stream = StringIO("abcdef")
while chunk := stream.read(2):
    print(chunk)
  1. Each condition reads at most two characters and binds them to chunk. Nonempty strings enter the body.
  2. At end of stream, read returns an empty string. That false value stops the loop without printing an extra line.
  3. The same structure can process file chunks, with a context manager managing the real file lifetime.
  4. Expected output: ab cd ef

Avoid repeated normalisation

Keep cleaned nonempty entries from a list.

raw = [" John ", " ", " James"]
cleaned = [name for text in raw if (name := text.strip())]
print(cleaned)
  1. For each text, strip computes the cleaned name. The filter rejects an empty result and the output expression keeps the other results.
  2. Each entry is stripped once. Unlike the comprehension loop variable, the assignment-expression target binds in the containing scope.
  3. Use this for simple input cleanup, but use a normal loop when several validation rules need separate explanations.
  4. Expected output: ['John', 'James']

Best practices

  • Parenthesise the assignment when comparing its result: (count := len(items)) > 3 stores the length, whereas count := len(items) > 3 stores a Boolean.
  • Use this sparingly. Combining several assignments and conditions into one expression can make debugging harder.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading