List Comprehension in Python
A list comprehension builds a new list in a single, compact expression, combining a loop and an optional condition into one line. It's Python's preferred way to write "transform every item in this collection" or "keep only the items matching a condition," replacing what would otherwise take several lines with an explicit loop.
The basic form
[expression for item in iterable] is the whole pattern.
Python loops and collects
It loops over iterable, evaluates expression for each item, and gathers the results into a new list.
Add a condition to filter
[expression for item in iterable if condition] only includes items where condition is true.
The original is never touched
A comprehension always builds a brand new list, leaving the source iterable unchanged.
Nesting is possible but has limits
Comprehensions can nest for multi-level data, though a plain loop is usually clearer past two levels.
numbers = [1, 2, 3, 4, 5, 6] squares = [n ** 2 for n in numbers]print(squares) evens = [n for n in numbers if n % 2 == 0]print(evens)A list comprehension visits every item in the source iterable exactly once, so it's O(n) time. Because it builds a brand new list, it also uses O(n) additional space — unlike a generator expression, which produces items lazily without storing them all at once.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.