AI engineering glossary · Python core
What is list comprehension?
List comprehension: A compact expression that builds a new list by applying an expression to each item of an iterable, optionally with a filtering condition, written [expr for item in iterable if cond]. It replaces many simple loops.
List comprehension: an example
[n * n for n in range(6) if n % 2 == 0] gives [0, 4, 16].
List comprehension in Python
A short example you can run (Python 3.11). The output below is what it really prints.
prices = [499, 1299, 89, 2999]
with_gst = [round(p * 1.18) for p in prices]
expensive = [p for p in prices if p > 1000]
print(with_gst)
print(expensive)Output
[589, 1533, 105, 3539] [1299, 2999]
Related terms
More Python core terms
Where you learn it
List comprehension is part of the AI Engineering Program, which teaches it with notes, a hands-on lab and an exam. The first lesson is free.