Python list comprehension provides a compact way to create a new
list from an iterable such as another list,
range(), string, tuple, or other sequence.
A list comprehension combines an expression with a for loop inside square brackets. A condition can also be added when only selected values are required.
List comprehensions are useful when the operation is simple and can be expressed clearly in one statement.
The basic syntax is:
[expression for item in iterable]
A condition can be added:
[expression for item in iterable if condition]
The expression produces the value that is added to the new list.
The following list comprehension creates a list containing the squares of numbers from 0 through 4.
squares=[
x**2
for x in range(5)
]
print(squares)
Output
[0, 1, 4, 9, 16]
For every value produced by range(5), the expression x**2 is evaluated and the result is added to the new list.
The same list can be created using a normal for loop and
append().
squares=[]
for x in range(5):
squares.append(x**2)
print(squares)
Output
[0, 1, 4, 9, 16]
squares=[
x**2
for x in range(5)
]
print(squares)
Both examples produce the same list. The list comprehension expresses the transformation in a shorter form.
For complex logic containing several statements, a normal loop can be easier to read.
An if condition can be placed after the for clause to include only values that match a condition.
Here we create a list containing only even numbers.
even_numbers=[
x
for x in range(10)
if x % 2 == 0
]
print(even_numbers)
Output
[0, 2, 4, 6, 8]
The expression adds x only when the remainder after division by 2 is 0.
We can combine filtering and transformation in the same list comprehension.
even_squares=[
x**2
for x in range(10)
if x % 2 == 0
]
print(even_squares)
Output
[0, 4, 16, 36, 64]
An if-else expression can be used when every input value should produce an output, but the output depends on a condition.
result=[
'Even' if x % 2 == 0 else 'Odd'
for x in range(1, 6)
]
print(result)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Notice the position of the condition:
value_if_true if condition else value_if_false
This conditional expression appears before the for clause.
List comprehension is commonly used to transform the elements of an existing list.
numbers=[2, 4, 6, 8]
new_list=[
x * 10
for x in numbers
]
print(new_list)
print(numbers)
Output
[20, 40, 60, 80]
[2, 4, 6, 8]
The list comprehension creates a new list. The original numbers list remains unchanged.
Strings can also be processed using list comprehension.
names=[
'Alex',
'Ronald',
'John'
]
lengths=[
len(name)
for name in names
]
print(lengths)
Output
[4, 6, 4]
The len() function is applied to every string.
names=[
'alex',
'ronald',
'john'
]
upper_names=[
name.upper()
for name in names
]
print(upper_names)
Output
['ALEX', 'RONALD', 'JOHN']
The following example keeps only names beginning with 'A'.
names=[
'Alex',
'Ronald',
'Anil',
'John'
]
result=[
name
for name in names
if name.startswith('A')
]
print(result)
Output
['Alex', 'Anil']
A user-defined function can be called for each element of a list comprehension.
def double_value(x):
return x * 2
numbers=[1, 2, 3, 4]
result=[
double_value(x)
for x in numbers
]
print(result)
Output
[2, 4, 6, 8]
The function is called once for each value in numbers.
More than one for clause can be used in a list comprehension.
pairs=[
(x, y)
for x in [1, 2]
for y in [10, 20]
]
print(pairs)
Output
[(1, 10), (1, 20), (2, 10), (2, 20)]
The second loop runs for every value produced by the first loop.
This is equivalent to:
pairs=[]
for x in [1, 2]:
for y in [10, 20]:
pairs.append((x, y))
print(pairs)
Nested list comprehension can create a 2D list.
my_list=[
[
j
for j in range(3)
]
for i in range(3)
]
print(my_list)
Output
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
The inner comprehension creates one row. The outer comprehension creates three separate rows.
rows=3
cols=4
matrix=[
[
0
for j in range(cols)
]
for i in range(rows)
]
print(matrix)
Output
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Each row is created separately, so changing one row does not automatically change the others.
List comprehension can convert a nested list into a single flat list.
my_list=[
[1, 2],
[3, 4],
[5, 6]
]
flat_list=[
item
for row in my_list
for item in row
]
print(flat_list)
Output
[1, 2, 3, 4, 5, 6]
The outer loop reads each row, and the inner loop reads each item from that row.
A condition can also be added while flattening a 2D list.
This example collects only values greater than 3.
my_list=[
[1, 2],
[3, 4],
[5, 6]
]
result=[
item
for row in my_list
for item in row
if item > 3
]
print(result)
Output
[4, 5, 6]
Both list comprehension and the
map() function can apply an operation to every element.
numbers=[1, 2, 3, 4]
squares=[
x**2
for x in numbers
]
print(squares)
Output
[1, 4, 9, 16]
def square(x):
return x**2
numbers=[1, 2, 3, 4]
squares=list(
map(square, numbers)
)
print(squares)
Output
[1, 4, 9, 16]
List comprehension is often convenient when the transformation can be expressed directly. map() is useful when an existing function should be applied to every item.
Both list comprehension and the
filter() function can select matching elements.
numbers=[1, 2, 3, 4, 5, 6]
even=[
x
for x in numbers
if x % 2 == 0
]
print(even)
Output
[2, 4, 6]
def is_even(x):
return x % 2 == 0
numbers=[1, 2, 3, 4, 5, 6]
even=list(
filter(is_even, numbers)
)
print(even)
Output
[2, 4, 6]
Use the form that makes the logic easiest to understand for the program being written.
When if is used only to filter values, it appears after the for clause.
even=[
x
for x in range(10)
if x % 2 == 0
]
A filtering condition appears after the loop:
[
x
for x in numbers
if x > 0
]
A conditional expression that chooses between two output values appears before the loop:
[
'Positive' if x > 0 else 'Zero or Negative'
for x in numbers
]
List comprehension is useful for compact transformations and filtering, but shorter code is not always clearer code.
When the logic requires several conditions, statements, or intermediate calculations, a normal for loop can be easier to understand and maintain.
[expression for item in iterable].if condition after the loop to filter values.value1 if condition else value2 before the loop when every item must produce a result.for clauses can be used for nested loops.for clauses.append().map() and filter() provide alternative approaches for transformations and filtering.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.