Skip to the solution
EasyDSA9 min read

What is the walrus operator?

110 views

The problem

Question presented to candidate: "What is the walrus operator, :=? Show me one place where it makes code genuinely better, and one place where you would not use it."

What a strong answer should cover:

  • := is an assignment expression (PEP 572, Python 3.8): it binds a name and evaluates to the value, so it can sit inside if, while, comprehensions and calls, where a normal = statement cannot.
  • The good uses: a read loop while (chunk := f.read(n)):, keeping a regex match you just tested, and computing a value once in a comprehension that both filters on it and keeps it.
  • Precedence: it binds more loosely than comparisons, so if n := len(a) > 3 stores a boolean; parenthesise (n := len(a)) > 3.
  • Scope: inside a comprehension the target binds in the enclosing function or module scope (the loop variable does not leak, the walrus target does).
  • Restrictions: not a bare statement, only plain names as targets (no attributes or subscripts), cannot rebind a comprehension iteration variable, not inside a comprehension in a class body.

Code / implementation expected: Yes β€” a short before/after, for example a comprehension that calls an expensive function once instead of twice.

  • walrus

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThe good uses: read loops, regex matches, compute-once comprehensions, any() witness
PythonScope, precedence and where := is a SyntaxError

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 33 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How does exception handling work in Python?

Continue