List Comprehension in Python –
Complete Notes
What is List Comprehension?
List comprehension is a concise way to create lists in Python using a single line of code.
Syntax:
[expression for item in iterable if condition]
Why Use List Comprehension?
- Shorter and more readable code
- Faster than traditional for-loops
- Clean and expressive syntax
1. Basic Example
Traditional:
squares = []
for x in range(5):
[Link](x * x)
List Comprehension:
squares = [x * x for x in range(5)]
# Output: [0, 1, 4, 9, 16]
2. With Condition (Filtering)
evens = [x for x in range(10) if x % 2 == 0]
# Output: [0, 2, 4, 6, 8]
3. With Else (Inline If-Else)
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
# Output: ['even', 'odd', 'even', 'odd', 'even']
4. Nested Loops
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
# Output: [(1, 3), (1, 4), (2, 3), (2, 4)]
5. List of Characters from a String
chars = [ch for ch in "Python"]
# Output: ['P', 'y', 't', 'h', 'o', 'n']
6. Convert Celsius to Fahrenheit
celsius = [0, 10, 20, 30]
fahrenheit = [(temp * 9/5) + 32 for temp in celsius]
# Output: [32.0, 50.0, 68.0, 86.0]
7. Remove Vowels from a String
text = "education"
no_vowels = [char for char in text if char not in "aeiou"]
# Output: ['d', 'c', 't', 'n']
8. Flatten a Nested List
nested = [[1, 2], [3, 4], [5]]
flat = [num for sublist in nested for num in sublist]
# Output: [1, 2, 3, 4, 5]
9. Using Functions in List Comprehension
def square(n):
return n * n
squares = [square(x) for x in range(6)]
# Output: [0, 1, 4, 9, 16, 25]
10. With Multiple Conditions or Inline If-Else
labels = ["small" if x < 5 else "medium" if x < 10 else "large" for x in range(12)]
# Output: ['small', ..., 'large']
11. Remove Duplicates and Sort
numbers = [3, 1, 2, 3, 4, 1]
unique_sorted = sorted({x for x in numbers})
# Output: [1, 2, 3, 4]
When NOT to Use List Comprehension
- Avoid for complex logic
- Avoid if readability is more important than brevity
- Use loops when multiple statements are needed
Practice Ideas
1. Squares of odd numbers from 1 to 20
2. Extract digits from 'a1b2c3'
3. Filter words > 4 letters
4. Multiplication table of 5
5. Convert words to uppercase