List comprehension is a concise and elegant way to create lists in Python.
✅ It’s shorter, faster, and more readable than using a traditional
for
loop.
[expression for item in iterable if condition]
Parts:
expression
: What to do with each item (e.g., x*x
)
item
: The variable representing each element in the iterable
iterable
: A sequence (like list, range, string, etc.)
condition
(optional): A filter for including items
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
chars = [char for char in "Python"]
print(chars) # Output: ['P', 'y', 't', 'h', 'o', 'n']
names = ["Abhi", "John", "Sara"]
lowercase_names = [name.lower() for name in names]
print(lowercase_names) # ['abhi', 'john', 'sara']
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs) # Output: [(1, 3), (1, 4), (2, 3), (2, 4)]
if-else
in Expressionlabels = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(labels) # Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']
Imagine you’re at a fruit shop and want only apples in your basket, but want them in uppercase.
fruits = ["apple", "banana", "apple", "orange"]
only_apples = [fruit.upper() for fruit in fruits if fruit == "apple"]
# Output: ['APPLE', 'APPLE']
Traditional Loop | List Comprehension |
---|---|
More lines of code | One-liner and elegant |
Less readable when complex | More readable and Pythonic |
Slightly slower for small operations | Faster and optimized in most cases |
Fast way to generate or transform lists
Use with for
, if
, and even if-else
Avoid overcomplicating – use for clarity, not complexity