Definition
A concise, one-line syntax for creating new lists based on existing lists or ranges. It combines a for loop and an expression into a single set of square brackets.
Why It Matters
List comprehensions transform verbose, error-prone loops into elegant, readable code; mastering this Pythonic pattern reduces the ‘cognitive tax’ of data manipulation and makes complex transformations maintainable at scale.
Core Concepts
- Syntax:
[expression for item in iterable] - Efficiency: Typically faster and more readable than building a list with an empty list and a standard
forloop. - Transformation: The
expressiondefines what happens to eachitembefore it is added to the new list.
# Create a list of squares for numbers 1-10
squares = [x**2 for x in range(1, 11)]
# List comprehension with a condition
evens = [x for x in range(1, 11) if x % 2 == 0]