Interview Questions: Comprehensions, Lambda & Functional Tools
Comprehensions and lambda are where interviewers check whether you reach for Python's idioms naturally or still think in manual for-loops — and whether you know when a one-liner helps versus when it just compresses code into something unreadable. This set covers readability tradeoffs, the three comprehension flavors, lambda's single-expression limit, map()/filter() versus comprehensions, and the sorted() mechanics that come up in almost every practical coding interview.
1 When does a list comprehension improve readability, and when does it hurt it?
A comprehension improves readability when it replaces a short, simple for-loop whose only job is building a new list from an existing one — [x * 2 for x in nums] reads as "double every number" almost like English, faster than scanning a three-line loop with an empty list and an .append() call. It hurts readability once it needs more than one if, nests another comprehension inside it, or the expression itself is doing several unrelated things at once — at that point it becomes a single dense line that takes longer to decode than the loop it replaced would have taken to read. The practical rule: if you have to pause and mentally "unroll" the comprehension into a loop to understand it, it's already past the point where a real loop would have been clearer.
Treating "comprehensions are more Pythonic" as a rule that always wins, and cramming a multi-condition, multi-step transformation into one line just to avoid writing a for-loop.
Follow-up"You need to build a list of usernames from active users only, but skip anyone whose username is banned, using a lookup against a second list. Comprehension or loop?" (Either can work, but if the banned-check makes the condition multi-part and hard to read on one line, a plain loop with early continue is the more maintainable choice.)
2 How do you filter items inside a list comprehension, and how is that different from just mapping every item?
Adding an if clause at the end of a comprehension — [x for x in nums if x % 2 == 0] — filters which items make it into the result at all, while the expression before for controls what each surviving item becomes. The two are independent and can be combined: [x * 2 for x in nums if x % 2 == 0] both filters (only even numbers) and transforms (doubles them) in the same line. Without the if, every single item from the source is included after being transformed — that's a pure "map" with no filtering at all.
Confusing filtering with transforming — e.g. trying to "filter out" an item by transforming it to None instead of just excluding it with an if clause.
"What does [x * x for x in range(5) if x % 2 == 0] evaluate to?" ([0, 4, 16] — only 0, 2, 4 pass the filter, then each gets squared.)
3 When would you reach for a dict comprehension instead of a list comprehension?
Reach for a dict comprehension, {key_expr: value_expr for item in iterable}, when the result needs to be looked up by a label afterward — the same list-vs-dict decision from Chapter 8, just applied while building the collection instead of after. A classic case is turning two matching lists into a lookup table, or building a word-to-length mapping: {word: len(word) for word in words}. A plain list comprehension is the right call when you only need the values themselves, in order, with no need to look any of them up by a key later.
Building a list of tuples like [(word, len(word)) for word in words] and then manually scanning it for a matching first element, when a dict comprehension would give direct key lookup for free.
"What does {x: x * x for x in range(4)} evaluate to?" ({0: 0, 1: 1, 2: 4, 3: 9} — each number maps to its own square.)
4 What's a set comprehension good for that a list comprehension isn't?
A set comprehension, {expr for item in iterable}, automatically drops duplicates the same way any set does — it's the natural choice any time the goal is "give me every distinct X," like unique domains from a list of emails or unique tags across a batch of posts. A list comprehension keeps every result including repeats and preserves order; a set comprehension collapses repeats and gives up any guaranteed order in exchange. If the later code needs fast membership checks (x in result) on the output, a set comprehension is doubly the right call, since set membership checks are hash-based and effectively instant, same as Chapter 8's set lookups.
Building a list comprehension and then manually deduplicating it afterward (e.g. looping and checking "have I added this already"), when a set comprehension does it in the same line for free.
Follow-up"What does {x % 3 for x in range(6)} evaluate to?" ({0, 1, 2} — the remainders repeat, but a set keeps only the distinct values.)
5 What's the readability/performance tradeoff with nested comprehensions?
A nested comprehension, like flattening a list of lists with [x for row in matrix for x in row], runs at essentially the same speed as the equivalent nested for-loop — there's no hidden performance win, just a more compact expression of the exact same work. The tradeoff is entirely about readability: one level of nesting (flattening, or building a small multiplication table) is usually still scannable, but two or more levels, or nesting a comprehension with its own if clause inside another one, quickly becomes something that has to be read several times to parse correctly. At that point, a couple of explicit nested for-loops with real variable names communicate the same logic more clearly to the next person reading it — "readable" beats "clever" once nesting goes past one level.
Assuming a nested comprehension is faster than nested for-loops — it isn't; it's the same underlying work, just less legible past one level of nesting.
Follow-up"What does [x for row in [[1, 2], [3, 4]] for x in row] evaluate to?" ([1, 2, 3, 4] — the outer loop walks each row, the inner loop walks each value in that row, flattening the nested list.)
6 What is a lambda function, and why can it only contain a single expression?
A lambda is a small, unnamed function written inline as lambda parameters: expression — it takes input, evaluates exactly one expression, and returns that expression's result automatically, with no explicit return keyword. It's restricted to a single expression by design: a lambda is meant to be a throwaway piece of logic passed directly into something else (a key= argument, a filter() predicate), not a place to define multi-step logic with several statements, loops, or branching blocks. If the logic needs more than one expression's worth of work, that's the signal it should become a real, named function (introduced next chapter) instead of being forced into a lambda.
Trying to cram multiple steps into a lambda with semicolons or nested conditional expressions just to avoid writing a named function — that's fighting the tool instead of reaching for the right one.
Follow-up"What does (lambda x, y: x + y)(3, 4) evaluate to?" (7 — the lambda is defined and immediately called with 3 and 4.)
7 When is it appropriate to use a lambda versus a real (named) function?
A lambda is appropriate when the logic is short, used once (or in one spot), and is being handed directly to something else as an argument — the classic case being a sort key or a filter condition where naming the function would add more ceremony than value. A named function is the better choice the moment the logic is reused in more than one place, needs a descriptive name to be understood at a glance, or would benefit from more than one line/expression of logic. In short: lambda is for a "just this once, right here" piece of logic; a named function is for anything that will be called from multiple places or needs a name that documents what it does.
Red flagsAssigning a lambda to a variable name and calling it repeatedly like a regular function (square = lambda x: x ** 2 used all over the file) instead of just writing it as a real function once that's introduced.
"You need to square a number in exactly one spot, as a sort key. Lambda or named function?" (Lambda — it's a single-use, single-expression need, exactly what key=lambda x: x ** 2 is for.)
8 What does map() do, and how does it compare to an equivalent list comprehension?
map(function, iterable) applies function to every item in iterable and hands back a lazy map object, which is usually wrapped in list(...) to see the results — list(map(lambda x: x * 2, nums)) doubles every number in nums. A list comprehension, [x * 2 for x in nums], does the exact same transformation but reads more like plain English and doesn't need the extra list() wrapper or a separate lambda. Most Python style guides and most working Python developers consider the comprehension the more Pythonic choice for this case; map() tends to show up more when the transforming function is already named and defined elsewhere, so there's no lambda needed at all.
Reaching for map() with a lambda as a reflex in new code when the equivalent comprehension would be shorter and clearer — that's usually a sign of habits carried over from another language.
"What does list(map(lambda x: x * 2, [1, 2, 3])) evaluate to?" ([2, 4, 6] — each number doubled, same result as [x * 2 for x in [1, 2, 3]].)
9 What does filter() do, and how does it compare to a comprehension with an if clause?
filter(function, iterable) keeps only the items from iterable for which function returns a truthy value, and like map(), it hands back a lazy object that's normally wrapped in list(...): list(filter(lambda x: x > 2, nums)). A comprehension with just an if clause and no transformation, [x for x in nums if x > 2], does the identical job and is generally considered the more readable, more Pythonic option for the same reason as map() versus a comprehension. filter() earns its keep in this chapter's project-style code specifically when the predicate itself is a lambda checking several conditions at once (blank name, blank email, invalid age) — at that point, filter(lambda r: ..., records) reads as "keep the records passing this whole rule," which can be clearer than cramming the same multi-part condition into a comprehension's if.
Believing filter() is required to filter a list — a comprehension's if clause does the same job and is usually the more idiomatic default.
"What does list(filter(lambda x: x > 2, [1, 2, 3, 4])) evaluate to?" ([3, 4] — only the items greater than 2 survive.)
10 How does the key= parameter work in sorted(), and why is lambda so often paired with it?
sorted(iterable, key=some_function) doesn't sort the raw items directly — instead, it calls some_function on every item first, and sorts based on those returned values while keeping each original item in place. This is exactly why lambda pairs so naturally with key=: the "what to sort by" logic is almost always a short, single-use expression (grab one field off a dict, compute a length, negate a number) that would be overkill to define as a separate named function just for one sort call. sorted(people, key=lambda p: p["age"]) reads as "sort people by their age field" in one line, with no extra function definition needed anywhere else in the file.
Believing key= transforms the actual items being returned — it only controls the sort order; the original items come back unchanged.
"Given people = [{'name': 'Bo', 'age': 30}, {'name': 'Al', 'age': 25}], what name is first in sorted(people, key=lambda p: p['age'])?" ('Al' — sorted ascending by age, and 25 is smaller than 30.)
11 What's the difference between sorted() and .sort()?
sorted(some_list) is a function that builds and returns a brand-new sorted list, leaving the original list completely untouched. some_list.sort() is a method that sorts the list in place and returns None — the original list itself is rearranged, and there's nothing meaningful to capture from the call. A very common beginner mistake is writing result = my_list.sort() expecting result to hold the sorted list, when it actually holds None because .sort() mutates my_list directly instead of returning anything useful. Use sorted() when the original order needs to be preserved elsewhere; use .sort() when mutating the list directly is fine or even desired.
Writing x = my_list.sort() and then using x as if it were the sorted list — it's None, and the real sorted list is my_list itself, now mutated.
"Given lst = [3, 1, 2], what does lst.sort() return, and what is lst afterward?" (Returns None; lst is now [1, 2, 3], mutated in place.)
12 What's a common mistake people make trying to put a statement inside a lambda?
A lambda can only hold an expression — something that evaluates to a value — never a statement, which is why trying to write lambda x: print(x) mostly "works" (print is technically a function call, which is an expression) but lambda x: x = 5 or lambda x: if x > 0: return x both raise a SyntaxError immediately, because assignment and if/return blocks are statements, not expressions. The reliable fix at this course's level for "I need a condition inside a lambda" is Python's conditional expression syntax, lambda x: "pos" if x > 0 else "neg" — that's still a single expression, just one that branches, unlike a full if/else block.
Trying to assign a variable, use a full if/elif/else block, or write a for loop inside a lambda body — all of those are statements, and none of them are legal inside a lambda's single expression.
"Is lambda x: x if x > 0 else -x valid Python, and what does calling it with -5 return?" (Yes, it's valid — a conditional expression is still one expression — and it returns 5.)
13 How would you sort a list of dictionaries by a field in descending order?
Pass both key= and reverse=True to sorted(): sorted(people, key=lambda p: p["score"], reverse=True) sorts by the "score" field, highest first. reverse=True simply flips the final order after the sort key has been applied — it doesn't change what's being sorted by, just the direction. This combination is exactly how a leaderboard or "top sellers" report gets built from a list of records: pick the field to rank by with key=, and pick the direction with reverse=.
Trying to negate the sort key itself for descending order on non-numeric fields (e.g. attempting key=lambda p: -p["name"], which fails on strings) instead of just using reverse=True, which works for any sort key.
"Given nums = [5, 2, 9, 1], what does sorted(nums, reverse=True) evaluate to?" ([9, 5, 2, 1] — sorted highest to lowest.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.