Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Transforming Collections with Comprehensions

Welcome back! In the previous lesson, you wrote functions that take product data and return useful results. You also saw how a loop can build a new list without changing the original one. Today you’ll learn a compact Python syntax for that kind of work: comprehensions.

By the end of this lesson, you’ll be able to create a list or dictionary from another collection, transform its values, and keep only items that meet a condition. These patterns will be useful when preparing product data for the storefront and, later, for API responses. Allow about 35–40 minutes, including the video and reading.


Build a list from a loop

Imagine you have product records and need a list of their SKUs. A familiar approach is to start with an empty list and append one SKU per product:

products = [
    {"sku": "A10", "name": "Notebook", "price_cents": 750, "in_stock": True},
    {"sku": "B20", "name": "Pen", "price_cents": 125, "in_stock": False},
    {"sku": "C30", "name": "Desk lamp", "price_cents": 2400, "in_stock": True},
]

skus = []
for product in products:
    skus.append(product["sku"])

print(skus)  # ['A10', 'B20', 'C30']

A list comprehension puts the value to collect and the loop header inside square brackets:

skus = [product["sku"] for product in products]

Read it as “collect each product’s SKU, for each product in products.” The expression before for determines each output element. The for clause supplies the input elements. Python creates a new list; it does not remove or alter records in products.

Watch the selected parts of Corey Schafer’s Python Tutorial: Comprehensions – How they work and why you should be using them. The loop-to-comprehension comparison is the key idea; you can skip the detour into map() and lambda.

Python Tutorial: Comprehensions - How they work and why you should be using them

Corey Schafer shows how a list comprehension takes over the job of a loop that builds a list, then adds a condition to select items.

Watch loops and transformations to see where the output expression goes. Then jump to filtering items; focus on why the if clause comes after the for clause.

The expression can do more than copy a value. Using the same products list, this creates uppercase names:

names = [product["name"].upper() for product in products]
print(names)  # ['NOTEBOOK', 'PEN', 'DESK LAMP']

This resembles transforming an array into a new array in JavaScript: each input item contributes a calculated output item. In Python, the expression appears before the loop clause, even though Python evaluates it once for each item.


Filter items—or give them different values

Sometimes you want fewer output items, not just different values. Add an if after the loop clause to decide whether an item belongs in the result:

available_skus = [
    product["sku"]
    for product in products
    if product["in_stock"]
]

print(available_skus)  # ['A10', 'C30']

For each product, Python checks product["in_stock"]. If it is true, Python adds that product’s SKU. If it is false, that product contributes nothing to the result. The line breaks are only for readability; this is one comprehension.

Filtering differs from choosing an output value for every input item. Suppose a product listing should show either the name or "Sold out":

labels = [
    product["name"] if product["in_stock"] else "Sold out"
    for product in products
]

print(labels)  # ['Notebook', 'Sold out', 'Desk lamp']

Here, if ... else ... is part of the output expression, before for. Every product still contributes one label. Compare the two shapes:

  • [expression for item in collection if condition] filters: an item may be omitted.
  • [value_if_true if condition else value_if_false for item in collection] chooses a value: every item contributes a result.

Read the “Filter Values From a List” subsection of Real Python’s Python List Comprehension: Tutorial With Examples. It develops both forms with examples; pay particular attention to whether a condition removes an item or replaces its output value.

Python List Comprehension: Tutorial With Examples

Real Python explains the difference between filtering after for and choosing an output with if ... else before for.

In “Supercharging Your Python List Comprehensions,” find “Filter Values From a List.” Start with the paragraph beginning “The most common way to add conditional logic,” and read filtering and replacement through the explanation of the example that replaces negative prices with zero. Watch where the condition sits in each form.

The distinction matters when preparing data for a UI. A filtered list could contain only purchasable products; a list of labels could retain every product while displaying its availability.


Build a dictionary with keys and values

A list comprehension produces a list because it uses square brackets. A dictionary comprehension uses curly braces and specifies both a key and a value before its loop clause:

price_by_sku = {
    product["sku"]: product["price_cents"]
    for product in products
}

print(price_by_sku)  # {'A10': 750, 'B20': 125, 'C30': 2400}

For each product, Python evaluates the expression to the left of the colon for the key and the expression to the right for the value. The resulting dictionary lets you look up a price with, for example, price_by_sku["A10"].

This is the dictionary version of creating {} and assigning one entry on each loop iteration:

price_by_sku = {}
for product in products:
    price_by_sku[product["sku"]] = product["price_cents"]

The image below highlights the same relationship using a loop that calculates powers of two. Notice that range(1, 10) supplies the integers 1 through 9, and that ** means exponentiation in Python.

Color-coded parts of a `for` loop are matched to a dictionary comprehension: the loop supplies each integer, while the key–value expression creates its dictionary entry.

Watch the dictionary segment of the same Corey Schafer video. It uses zip() to pair elements from two lists; the important part here is how the paired values become dictionary keys and values, and how a final if can omit entries.

Python Tutorial: Comprehensions - How they work and why you should be using them

Return to Corey Schafer’s comprehension tutorial for the dictionary example, which extends the list pattern to key–value pairs.

Watch dictionary comprehensions. Focus on the key: value expression inside the braces and the optional condition at the end; you do not need to use zip() for the product examples in this lesson.

You can filter a dictionary comprehension just as you filtered a list:

available_prices = {
    product["sku"]: product["price_cents"]
    for product in products
    if product["in_stock"]
}

print(available_prices)  # {'A10': 750, 'C30': 2400}

You can also transform an existing dictionary. Its .items() method supplies each key and its corresponding value as a pair:

adjusted_prices = {
    sku: cents + 100
    for sku, cents in price_by_sku.items()
    if cents >= 500
}

print(adjusted_prices)  # {'A10': 850, 'C30': 2500}
print(price_by_sku["A10"])  # 750

This example selects prices of at least 500 cents and adds 100 cents to each selected value. price_by_sku remains unchanged: the comprehension builds a separate dictionary. That makes it suitable for deriving a view of data without silently changing the source.

Dictionary keys must be unique. If two input records produce the same SKU key, the later value replaces the earlier one in the result. A comprehension does not validate that your source data has unique SKUs; use a more explicit approach when a duplicate should be treated as an error.


Choose clarity over compression

Comprehensions are most useful when the task is easy to state: produce these values from these items, optionally keeping only some. A short transformation and a condition often fit well. If you need several decisions, error handling, or changes to other objects, a regular loop is usually easier to inspect.

They also work naturally inside the functions from your previous lesson:

def available_product_skus(products):
    return [
        product["sku"]
        for product in products
        if product["in_stock"]
    ]


print(available_product_skus(products))  # ['A10', 'C30']

The function names the task; the comprehension builds and returns its result. There is no need to call append() or print from inside the function. For an empty input list, this function returns [].

Comprehensions create their output collections immediately. They are not inherently better merely because they use fewer lines. When a loop communicates the business rule more clearly, keep the loop.


What to carry forward

A list comprehension uses [expression for item in collection] to build a new list. Add an if at the end to omit items; put if ... else ... in the expression to choose an output for every item. A dictionary comprehension uses {key: value for item in collection}, with the same option to filter. Both are concise ways to transform data without changing the source collection.

Next, you’ll work on diagnosing Python errors with tracebacks and debugger breakpoints—useful tools when a transformation encounters an unexpected value or a missing dictionary key.

Can't find a good explanation? Sign up and we'll make it for you

Sign up