Comprehensions
A comprehension constructs a list, dictionary or set from an existing iterable in a single expression. It is the conventional form in Python for building one sequence from another, and is generally both shorter and faster than the equivalent loop, because the list is built without repeated method lookups.
[60, 24, 90, 14]
The expression before for is evaluated once per element and its result becomes
the corresponding element of the new list. The original list is unchanged.
Filtering
An if clause at the end restricts which elements are included. Elements for
which the condition is false are omitted entirely; the result is therefore
shorter than the input.
[30, 45]
Transformation and filtering combine in one expression. The if is applied
first, and the leading expression is evaluated only for elements that pass.
['TP53', 'EGFR']
A conditional expression may also appear in the leading position, which selects
between two values rather than filtering. The two forms are distinct: the
leading if ... else chooses a value; the trailing if chooses membership.
['pass', 'fail', 'pass']
Dictionary and set comprehensions
The same syntax builds a dictionary when the body is a key: value pair, and a
set when it is a single expression in braces. Building a lookup table from two
parallel sequences is a frequent use.
{'TP53': 120, 'BRCA1': 88}
{'G', 'C', 'T', 'A'}
Nested iteration
A comprehension may contain more than one for clause. They are evaluated left
to right, in the same order as the equivalent nested loops, with the rightmost
varying fastest.
['AA', 'AC', 'AG', 'AT', 'CA', 'CC', 'CG', 'CT']
Nesting beyond two levels is difficult to read and should be written as an ordinary loop.
Generator expressions
Replacing the brackets with parentheses produces a generator, which yields
elements one at a time instead of building the whole sequence in memory. When
the result is consumed immediately by sum, max, any or all, a generator
avoids constructing an intermediate list.
75 True
When not to use a comprehension
A comprehension should perform one transformation and fit on one or two lines.
If it requires several conditions, a try block, or side effects such as
printing or writing to a file, write an explicit loop instead.
Task
Write passing_genes(records). It receives a list of (gene, depth) tuples and
returns the gene names whose depth is 30 or more, uppercased and sorted
alphabetically. Use a comprehension; the tuple unpacks directly in the for
clause.
Test cases · 2
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | tp53 120 brca1 12 egfr 45 | ['EGFR', 'TP53'] |
| 2 | stdin | kras 29 myc 30 | ['MYC'] |
Hints · 2
01Hint
Unpack the tuple directly in the comprehension: for gene, depth in records.
02Hint
sorted() around the comprehension handles the ordering.