List Comprehension in Python

Last Updated : 7 May, 2026

List comprehension is a concise way to create new lists by applying an expression to each item in an existing iterable like a list, tuple or range. It helps to write clean, readable and efficient code compared to traditional loops.

Suppose you want to square every number in a list:

Python
a = [2, 3, 4, 5]
res = [val ** 2 for val in a]
print(res)

Output
[4, 9, 16, 25]

Explanation: res = [val ** 2 for val in a] use list comprehension to create a new list by squaring each number in a.

Syntax

[expression for item in iterable if condition]

Parameters:

  • expression: operation or value to include in the new list.
  • item: current element from the iterable.
  • iterable: sequence like a list, tuple or range.
  • if condition (optional): filter to include only items that satisfy the condition.

Conditional Statements in List Comprehension

List comprehensions can use conditions to select or transform items based on specific rules. This allows creating customized lists more concisely and improves code readability and efficiency.

Example 1: This code uses a list comprehension with a condition to create a new list with only even numbers from list a.

Python
a = [1, 2, 3, 4, 5]
res = [val for val in a if val % 2 == 0]
print(res)

Output
[2, 4]

Example 2: Here, list comprehension is used with a condition to create a new list with numbers greater than 10 from list b.

Python
b = [5, 12, 7, 18, 3, 20]
res = [val for val in b if val > 10]
print(res)

Output
[12, 18, 20]

Examples

1. Creating a list from a range: One can quickly create a list of numbers within a specific range using list comprehension.

Python
a = [i for i in range(10)]
print(a)

Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2. Using nested loops: A list of all coordinate pairs in a 3x3 grid can be generated by combining two loops inside a list comprehension.

Python
c = [(x, y) for x in range(3) for y in range(3)]
print(c)

Output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

3. Flattening a list of lists: A nested list (matrix) can be transformed into a single flat list by iterating through each sublist and its elements.

Python
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
res = [val for row in mat for val in row]
print(res)

Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

For Loop vs List Comprehension

For LoopList Comprehension
Uses multiple lines of codeUses a single line of code
Requires manual appending of elementsCreates the list directly
Better for complex logic and conditionsBetter for simple and concise operations
More readable for long operationsMore compact and faster to write
Comment