A comprehension builds a list from an existing sequence in one expression.
depths = [30, 12, 45, 7]
doubled = [depth * 2 for depth in depths]
print(doubled)
This is the same as building the list with a loop, and is the normal way to write it in Python.
Filtering
An if at the end keeps only the items that match.
depths = [30, 12, 45, 7]
passing = [depth for depth in depths if depth >= 30]
print(passing)
Transforming and filtering together
genes = ["tp53", "brca1", "egfr"]
print([gene.upper() for gene in genes if len(gene) == 4])
Dictionary and set comprehensions
The same syntax builds dictionaries and sets.
genes = ["TP53", "BRCA1"]
depths = [120, 88]
lookup = {gene: depth for gene, depth in zip(genes, depths)}
print(lookup)
sequence = "ATGGCCA"
print(sorted({base for base in sequence}))
When not to use one
A comprehension should fit on one or two lines and do one thing. If it needs
several conditions, or a try, write a normal loop.
Task
Write passing_genes(records). It receives a list of (gene, depth) tuples and
returns a list of gene names whose depth is 30 or more, uppercased, sorted
alphabetically. Use a comprehension.
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.