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,{}withkey: valuea dict,{}with single values a set;()gives a lazy generator expression, not a "tuple comprehension". - A trailing
iffilters items;x if cond else yin front transforms every item β different positions, different jobs. - Several
forclauses 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.