Tutorials Logic, IN info@tutorialslogic.com

Python Comprehensions: List, Dict, Set, and Generator

Comprehension Basics

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.

List Comprehensions

A list comprehension returns a new list. It is useful for mapping, filtering, or cleaning a list without writing append() repeatedly.

  • Put the result expression first.
  • Put the loop after the result expression.
  • Add if at the end only when items should be filtered.

Filter and Transform Prices

Filter and Transform Prices
prices = [499, 799, 1299, 199]

discounted = [round(price * 0.9) for price in prices if price >= 700]

print(discounted)
Output
[719, 1169]

Only prices at least 700 are included, then each selected price gets a 10 percent discount.

Dictionary Comprehensions

A dictionary comprehension creates key-value pairs. It is useful when you want fast lookup data from a list of records.

  • Return key and value separated by a colon.
  • Keep keys unique, because later values replace earlier values with the same key.
  • Use dictionary comprehensions for lookup tables and transformed records.

Build a Price Lookup

Build a Price Lookup
products = [
    ("book", 499),
    ("course", 999),
    ("notebook", 80),
]

price_by_name = {name: price for name, price in products}

print(price_by_name["course"])
Output
999

The product name becomes the key, so the price can be read quickly by name.

Set Comprehensions

A set comprehension creates unique values. It removes duplicates automatically and does not keep a reliable order.

  • Use set comprehensions for unique tags, IDs, categories, or normalized words.
  • Do not use a set when the order of results matters.

Collect Unique Domains

Collect Unique Domains
emails = ["maya@example.com", "ravi@test.com", "admin@example.com"]
domains = {email.split("@")[1] for email in emails}

print(sorted(domains))
Output
['example.com', 'test.com']

Each email is split once, and the set keeps only unique domains.

Generator Expressions

A generator expression produces values one at a time instead of creating the whole collection in memory.

  • Use generator expressions with sum(), any(), all(), min(), and max().
  • Use a list comprehension when you need to reuse or inspect the full list.

Sum Without a List

Sum Without a List
orders = [120, 250, 80, 310]

large_order_total = sum(order for order in orders if order >= 200)

print(large_order_total)
Output
560

sum() consumes matching values as they are produced, so no temporary list is needed.

Skill check

Can You Read Comprehensions?

5 checks
  • Use comprehensions only when the expression stays readable.
  • Use list comprehensions when a new list is needed.
  • Use dictionary comprehensions for key-value lookup data.
  • Use set comprehensions when uniqueness matters.
  • Use generator expressions when a function can consume values one at a time.

Comprehension Readability Traps

  • Forcing complex logic into one line

    Use a normal loop when the comprehension becomes hard to read.
  • Forgetting filter position

    Place the if filter after the for clause in a standard comprehension.
  • Creating a list when a generator is enough

    Use parentheses for generator expressions when values can be consumed lazily.

Try this next

Rewrite a Loop Compactly

0 of 3 completed

  1. Create a list of squares from 1 to 5.
  2. Keep only names that start with A and convert them to title case.
  3. Turn one long comprehension into a normal loop with the same result.

Questions About Comprehension

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.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.