List comprehension in Python provides a concise way to create lists.
It consists of brackets containing an expression
followed by a for
clause, then zero or more for or if
clauses.
The result will be a new list
resulting from evaluating the expression in the context of the for
and if
clauses which follow it.
Basic syntax
[expression for item in iterable if condition]
Basic List Comprehension
Create a list of squares for 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]
List Comprehension with Condition
Create a list of even numbers from 0 to 9.
evens = [x for x in range(10) if x % 2 == 0] print(evens) # [0, 2, 4, 6, 8]
Nested List Comprehension
Flatten a 2D list into a 1D list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened = [num for row in matrix for num in row] print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Point to note here, the first row loop get executed, the value of row pass to next loop and get accessed, which finally retun the num.
List Comprehension with Function
Apply a function to each element in a list.
def square(x): return x * x numbers = [1, 2, 3, 4, 5] squares = [square(x) for x in numbers] print(squares) # [1, 4, 9, 16, 25]
Multiple Conditions
Create a list of numbers from 0 to 99 that are divisible by both 3 and 5.
div_by_3_and_5 = [x for x in range(100) if x % 3 == 0 and x % 5 == 0] print(div_by_3_and_5) # [0, 15, 30, 45, 60, 75, 90]
List comprehensions can be powerful tools for creating and manipulating lists in a concise, readable manner.
They can replace loops and map/filter functions with a single line of code.