Skip to main content

Set Comprehensions

Set comprehensions use the same syntax as list comprehensions but use curly braces {} instead of square brackets []. The key difference is that sets automatically handle uniqueness—any duplicate values generated by the expression are discarded.

Syntax and Uniqueness​

We use set comprehensions when we want to ensure our final collection contains no duplicates.

fav_chais = [
"Masala Chai",
"Green tea",
"Masala ChaiLemon Chai",
"Green Tea",
"Elaichi Chai",
]

# Create a set of unique chais
unq_chai = {chai for chai in fav_chais}
print(unq_chai)

Output:

{'Green tea', 'Masala ChaiLemon Chai', 'Masala Chai', 'Green Tea', 'Elaichi Chai'}

Extracting Unique Data from Nested Structures​

Set comprehensions are incredibly useful for extracting unique values from complex data, such as finding all unique ingredients used across multiple recipes.

recipes = {
"Masala Chai": ["ginger", "cardamom", "clove"],
"Elaichi Chai": ["cardamom", "milk"],
"Spicy Chai": ["ginger", "black pepper", "clove"],
}

# Flatten the lists and keep only unique spices
unq_spices = {spice for ingredients in recipes.values() for spice in ingredients}
print(unq_spices)

Output:

{'cardamom', 'ginger', 'clove', 'milk', 'black pepper'}
Sets vs. Dicts

Both set and dictionary comprehensions use curly braces. The difference lies in the expression:

  • {x for x in ...} produces a set.
  • {key: val for x in ...} produces a dictionary.