Set Comprehensions

Concepts covered: Set Comprehension

A set comprehension is a list comprehension written in curly braces. {expression for item in iterable if condition} evaluates the expression for each item that passes the condition and adds the result to a new set. Duplicates collapse as the set is built, and no intermediate list is created. A colon in the expression, as in {k: v for ...}, makes it a dict comprehension instead. The examples below run over 5 clickstream events.

events = [
    {"user_id": 8814, "event": "checkout", "country": "de", "tags": ["promo"]},
    {"user_id": 1203, "event": "view", "country": "DE", "tags": []},
    {"user_id": 8814, "event": "checkout", "country": "fr", "tags": ["promo", "mobile"]},
    {"user_id": 5521, "event": "checkout", "country": None, "tags": ["mobile"]},
    {"user_id": 7740, "event": "checkout", "country": "FR ", "tags": ["promo"]},
]

buyers = {e["user_id"] for e in events if e["event"] == "checkout"}
countries = {e["country"].strip().upper() for e in events if e["country"]}
tags = {t for e in events for t in e["tags"]}
event_types = frozenset(e["event"] for e in events)

print(sorted(buyers))
print(sorted(countries))
print(sorted(tags))
print(type(event_types).__name__, len(event_types))

Output:

[5521, 7740, 8814]
['DE', 'FR']
['mobile', 'promo']
frozenset 2

Each line exercises one part of the syntax. buyers filters on the event type and keeps only the id, so user 8814's 2 checkouts become 1 element. countries shows the order in which the clauses run. The if is tested first, so .strip() never reaches the None. Normalising inside the expression is what merges "de", "DE", "fr" and "FR " into 2 codes. tags uses 2 for clauses, read left to right like nested loops, to flatten every event's tag list into a single set.

There is no frozenset comprehension

Curly braces always produce a mutable set. For a frozen result, pass a generator expression to the constructor, as event_types does with frozenset(e["event"] for e in events). The generator hands over 1 element at a time, so nothing is stored in between. Wrapping a list comprehension in set() reaches the same set by a longer route: it builds a full list with every duplicate included, then hashes each of its elements into the set.

FormIntermediate listResult
{f(x) for x in xs}Noneset
set(f(x) for x in xs)Noneset
set([f(x) for x in xs])Yes, duplicates includedset
frozenset(f(x) for x in xs)Nonefrozenset
[f(x) for x in xs]The list is the resultlist, duplicates kept

Filters, conditionals and where they go

An if after a for drops items. An if/else before the first for keeps every item and chooses what to add for each one. Mixing the 2 up changes the size of the result, so a wrong count from a comprehension is the first sign to check which form was used.

labels = {"paid" if e["event"] == "checkout" else "free" for e in events}
paid_ids = {e["user_id"] for e in events if e["event"] == "checkout"}
promo_buyers = {e["user_id"] for e in events if e["event"] == "checkout"
                for t in e["tags"] if t == "promo"}
# labels: 2 elements, every event mapped to "paid" or "free"
# paid_ids: 3 elements, the view event dropped
# promo_buyers: 2 elements, 8814 and 7740

The third comprehension shows that an if can sit between for clauses and filter at that level of nesting before the inner loop runs. The expression has a cost to watch: it runs once per item, before deduplication. {fetch_segment(e["user_id"]) for e in events} over 50,000 events makes 50,000 calls even when only 3,000 users exist. Deduplicating the ids first, with {fetch_segment(u) for u in {e["user_id"] for e in events}}, makes 3,000. When a loop has to do 2 jobs at once, such as collecting ids while counting rejects, a plain for loop with .add() reads better than a comprehension with side effects.

Each wrong condition crashes for its own reason. e is None lets only the None through, so .split runs on None and fails in the expression. "@" in e fails in the filter itself, because in cannot search None. The guard has to test for None before anything else touches e. Lowercasing inside the expression is what makes Shop.io and shop.io one element.

About this lesson

This section is part of the Sets: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.