π List Comprehensions
List comprehension is a short and simple way to create a new list from an existing iterable.
πΉ Basic Syntax
[expression for item in iterable]Example
Normal approach:
numbers = [1, 2, 3, 4]
squares = []
for n in numbers:
squares.append(n ** 2)
print(squares)Using list comprehension:
numbers = [1, 2, 3, 4]
squares = [n ** 2 for n in numbers]
print(squares)[1, 4, 9, 16]π List Comprehension with Condition
Syntax
[expression for item in iterable if condition]You can add an if condition:
numbers = [1, 2, 3, 4, 5, 6]
even = [n for n in numbers if n % 2 == 0]
print(even) #[2, 4, 6]π List Comprehension with if-else
numbers = [1, 2, 3, 4]
result = ["Even" if n % 2 == 0 else "Odd" for n in numbers]
print(result) #['Odd', 'Even', 'Odd', 'Even']