List comprehension is one of Python’s most elegant and powerful features. It allows you to create new lists by applying an expression to each item in an existing iterable (like a list, tuple, or range), all in a single line of code.
Whether you're filtering data, transforming values, or flattening nested lists, list comprehensions make your code more readable and concise.
Here’s the general syntax:
[expression for item in iterable if condition]
expression: The value to store in the new list.
item: The variable representing each element in the iterable.
iterable: A sequence (like a list or range).
condition (optional): A filter that determines whether the item should be included.
squares = [x**2 for x in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]
# Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
# Output: ['HELLO', 'WORLD', 'PYTHON']
pairs = [(x, y) for x in range(3) for y in range(3)]
# Output: [(0, 0), (0, 1), (0, 2), (1, 0), ..., (2, 2)]
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4, 5, 6]
def square_even(x):
return x**2 if x % 2 == 0 else x
result = [square_even(x) for x in range(10)]
# Output: [0, 1, 4, 3, 16, 5, 36, 7, 64, 9]
While list comprehensions are concise, they can become hard to read if overused—especially with complex logic or deeply nested loops. In such cases, prefer regular for loops for clarity.
Here’s a quick challenge:
Create a list of all numbers from 1 to 50 that are divisible by both 3 and 5.
divisible = [x for x in range(1, 51) if x % 3 == 0 and x % 5 == 0]
# Output: [15, 30, 45]
List comprehensions are a Pythonic way to write clean, efficient code. Mastering them will help you write better scripts, especially in data processing and machine learning workflows.
Next up in the series: map and filter methods