Python – List Comprehension
List comprehension is a compact way to create lists in Python. It replaces the traditional for
loop with a single elegant line of code.
It improves readability, performance, and is widely used in data processing, filtering, and transformation.
Basic Syntax of List Comprehension
[expression for item in iterable if condition]
- expression: The item or operation to return
- item: Variable representing each element in the iterable
- iterable: A list, tuple, string, range, etc.
- condition: (optional) Filter to include specific items
1. Simple List Comprehension
Create a new list of items from another list.
Example:
fruits = ["apple", "banana", "cherry"]
new_list = [fruit.upper() for fruit in fruits]
print(new_list)
Output:
['APPLE', 'BANANA', 'CHERRY']
2. Using if
Condition
Filter items while creating the list.
Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)
Output:
[2, 4, 6]
3. With if...else
in Expression
Add conditional logic to the output.
Example:
nums = [1, 2, 3, 4]
labels = ["Even" if n % 2 == 0 else "Odd" for n in nums]
print(labels)
Output:
['Odd', 'Even', 'Odd', 'Even']
4. Using range()
and Math Operations
You can also perform calculations inside list comprehensions.
Example:
squares = [x**2 for x in range(6)]
print(squares)
Output:
[0, 1, 4, 9, 16, 25]
5. Nested List Comprehension
Used to flatten or process 2D lists.
Example: Flatten a matrix
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)
Output:
[1, 2, 3, 4, 5, 6]
6. Without Condition – Traditional vs Comprehension
Traditional for
loop:
result = []
for x in range(5):
result.append(x * 2)
print(result)
List comprehension:
result = [x * 2 for x in range(5)]
print(result)
Output (both):
[0, 2, 4, 6, 8]
Why Use List Comprehension?
Benefit | Description |
---|---|
Faster | Executes quicker than traditional loops |
Cleaner | Easier to read and write |
Functional Style | Fits into a functional programming approach |