List comprehension (Python)

« Back to Glossary Index

A List Comprehension is a syntactic construct in Python that enables the creation of new lists in a concise, expressive, and computationally efficient way. It combines an expression, one or more for loops, and optionally an if condition, all written in a single line of code. This technique replaces traditional iterative loops, improving code readability and reducing structural complexity.

The general structure is as follows:

[expression for element in sequence if condition]

Each component serves a specific role:

  • expression → defines how each element of the input sequence is transformed.
  • for element in sequence → iterates through the elements of the original collection.
  • if condition (optional) → filters elements that satisfy a given logical condition.

Basic Example

# Create a list containing the squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)
# ➜ [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

It is also possible to include a conditional statement to refine the result:

# Generate a list with the squares of even numbers only
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
# ➜ [0, 4, 16, 36, 64]

List comprehensions can be extended to other Python collections such as dictionaries (dict comprehensions) and sets (set comprehensions), which follow a similar syntax and enable declarative construction of data structures.

From a pedagogical and best-practice perspective, List Comprehensions are recommended when the transformation logic is short and easily interpretable, as they promote a more functional and expressive programming style. They contribute to writing Pythonic code—that is, code that is clear, elegant, and consistent with Python’s design philosophy.

« Back to Glossary Index