A comprehension builds a new collection from existing data in one compact expression.
Use a comprehension when the transformation is simple enough to read left to right: create this value for each item that passes this condition.
If the logic needs several steps, validation, or logging, use a normal loop instead of forcing everything into one line.
A list comprehension returns a new list. It is useful for mapping, filtering, or cleaning a list without writing append() repeatedly.
prices = [499, 799, 1299, 199]
discounted = [round(price * 0.9) for price in prices if price >= 700]
print(discounted)
[719, 1169]
Only prices at least 700 are included, then each selected price gets a 10 percent discount.
A dictionary comprehension creates key-value pairs. It is useful when you want fast lookup data from a list of records.
products = [
("book", 499),
("course", 999),
("notebook", 80),
]
price_by_name = {name: price for name, price in products}
print(price_by_name["course"])
999
The product name becomes the key, so the price can be read quickly by name.
A set comprehension creates unique values. It removes duplicates automatically and does not keep a reliable order.
emails = ["maya@example.com", "ravi@test.com", "admin@example.com"]
domains = {email.split("@")[1] for email in emails}
print(sorted(domains))
['example.com', 'test.com']
Each email is split once, and the set keeps only unique domains.
A generator expression produces values one at a time instead of creating the whole collection in memory.
orders = [120, 250, 80, 310]
large_order_total = sum(order for order in orders if order >= 200)
print(large_order_total)
560
sum() consumes matching values as they are produced, so no temporary list is needed.
Try this next
0 of 3 completed
No. A normal loop is better when the logic needs multiple steps, error handling, or comments to stay understandable.
Yes, but conditional expressions with else go before the loop, such as x if condition else y for item in items. Filters without else go after the loop.
Use one when you do not need the full list in memory and a function such as sum(), any(), or all() can consume values directly.
Explore 500+ free tutorials across 20+ languages and frameworks.