Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python comprehensions: build results without changing the input

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

A list comprehension builds a new list from an iterable using a transformation and optional filter.

Download Python source kit

Operation contract

The receipt import accepts positive exact integers and converts each accepted minor-unit amount to a display label. The fixture rejects booleans from this numeric field even though comparison alone would accept True. Both the filter and the representation policy are visible in one expression. It keeps input order and leaves the supplied sequence untouched.

Failure and ownership boundary

An outer list is new; objects returned directly from a comprehension could still be shared. A comprehension also materializes every result immediately. For a long stream, consider Python generators: lazy iteration does not make retained output free and define when input failures should surface. Nested comprehensions can multiply work; compact syntax does not change the number of combinations visited.

Working program

python
amounts = [125, 0, -10, True, 75]
labels = [f"minor:{amount}" for amount in amounts if type(amount) is int and amount > 0]
print(labels)
print(amounts)

Output

Output
['minor:125', 'minor:75']
[125, 0, -10, True, 75]

Costs and limits

For n values the fixture makes one pass and retains k labels, with O(n) iteration work and O(k) output entries. Formatting cost grows with each integer’s digits.

Common Mistakes

  • Do not hide a network call or state mutation inside a transformation.
  • A new result list does not imply its referenced objects are independent.

Connected lessons

Python conditions and loops: distinguish no value from an empty value, Python lists: slicing copies the outer sequence, not nested objects, Python generators: lazy iteration does not make retained output free.

python
comprehensions
Storage details