List Comprehension in Python
List comprehension is a concise way to create lists in Python.
It allows you to generate a new list by applying an expression to each item in an iterable,
optionally filtering items with a condition.
Basic Syntax:
[expression for item in iterable]
Example:
squares = [x*x for x in range(5)]
# Output: [0, 1, 4, 9, 16]
List Comprehension with Condition:
[expression for item in iterable if condition]
Example:
even_numbers = [n for n in range(10) if n % 2 == 0]
# Output: [0, 2, 4, 6, 8]
Nested List Comprehension:
matrix = [[i*j for j in range(3)] for i in range(3)]
# Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
With Else Condition:
["even" if x % 2 == 0 else "odd" for x in range(5)]
# Output: ["even", "odd", "even", "odd", "even"]
Key Advantages:
- More concise and cleaner code
- Often faster than traditional loops
- Easy to include conditions and transformations
When NOT to Use:
- When resulting code becomes hard to read
- When logic is too complex; better use loops