Skip to the solution
EasyDSA10 min read

What are list/dict/set comprehensions?

213 views

The problem

Question presented to candidate: "What are list, dict and set comprehensions in Python? Write a couple, tell me how they relate to a normal for loop, and when you would not use one."

What a strong answer should cover:

  • The shape [expression for item in iterable if condition]; [] builds a list, {} with key: value a dict, {} with single values a set; () gives a lazy generator expression, not a "tuple comprehension".
  • A trailing if filters items; x if cond else y in front transforms every item β€” different positions, different jobs.
  • Several for clauses read left to right like nested loops; a comprehension inside a comprehension builds a nested result.
  • Scope: the loop variable does not leak, but a walrus := binds in the enclosing scope; in a class body only the first iterable sees class names.
  • CPython detail: up to 3.11 a comprehension runs as a hidden nested function (<listcomp>); PEP 709 inlined list, dict and set comprehensions in 3.12.
  • When not to: side effects, deeply nested or multi-condition logic, or huge data where a generator expression avoids building the whole list.

Code / implementation expected: Yes β€” one list, one dict and one set comprehension, plus the equivalent loop for one of them.

  • comprehension

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

10 min read Β· 10 sections

Run the code

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

PythonList, set, dict and generator comprehensions side by side
PythonScope rules: no leaking, walrus, class bodies, eager vs lazy

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 31 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

What is duck typing in Python?

Continue