Guide Python Intermediate

12.12 Set Comprehensions

The same comprehension syntax as list comprehensions, but with {} instead of [], automatically deduplicating the result -- basic, conditional, and nested forms.

2 min read

The same comprehension syntax as lists (see 10.9 Traversing and List Comprehensions), but with {} instead of [] — automatically deduplicates the result.

Basic

>>> {x**2 for x in range(5)}
{0, 1, 4, 9, 16}

Conditional

>>> {x for x in range(10) if x % 2 == 0}
{0, 2, 4, 6, 8}

Nested

A comprehension inside another expression — here, extracting a set of unique values from a nested structure.

>>> matrix = [[1, 2], [2, 3], [3, 4]]
>>> {x for row in matrix for x in row}
{1, 2, 3, 4}

Quick Interview Answer

“A set comprehension is a list comprehension with {} instead of [] — same for/if clauses, same nesting rules — with one automatic side effect: whatever the expression produces gets deduplicated as it’s built, since the result is a set. That makes it the natural one-liner for extracting unique values out of a nested or filtered structure, without a separate set(...) call wrapped around a list comprehension.”

Common Mistakes

  • Writing [x for x in ...] when a unique result is actually wanted, then wrapping the whole thing in set(...) afterward — a set comprehension does both steps in one pass.
  • Assuming a set comprehension preserves the order elements were generated in — like any set, the result’s iteration order isn’t guaranteed.
  • Using an unhashable expression result (like building a list per iteration) inside a set comprehension — raises TypeError: unhashable type, same as adding that value to a set directly.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form