Learn Python
>>> data_structures.list_comprehension

List Comprehension in Python

#concept

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.

#how it works
1

The basic form

[expression for item in iterable] is the whole pattern.

2

Python loops and collects

It loops over iterable, evaluates expression for each item, and gathers the results into a new list.

3

Add a condition to filter

[expression for item in iterable if condition] only includes items where condition is true.

4

The original is never touched

A comprehension always builds a brand new list, leaving the source iterable unchanged.

5

Nesting is possible but has limits

Comprehensions can nest for multi-level data, though a plain loop is usually clearer past two levels.

#example
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)
Output
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
1[n ** 2 for n in numbers] loops over every number, squares it, and collects the results into a new list.
2[n for n in numbers if n % 2 == 0] loops over every number, but the if condition means only even numbers are actually added to the result.
3numbers itself is completely unchanged by either comprehension — both produce entirely new lists.
#complexity
time O(n)
space O(n)

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.

#use cases
Transforming every item in a collection in one readable line, instead of a longer explicit loop
Filtering a list down to only the items that satisfy a condition
Quickly building a list of computed values, like extracting one field from a list of dictionaries
Replacing common map()/filter() patterns with something most Python developers find more readable

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.