Module 09 β Sets & Comprehensions
Unique collections, and a faster, more Pythonic way to build lists and dictionaries.
Prerequisite: Module 08 β Dictionaries
After this lesson, you will be able to
- Create sets and use union, intersection, and difference
- Rewrite append-loops as list comprehensions
- Add a condition to a comprehension with if / if-else
- Write dictionary and set comprehensions
Concept & Syntax
A set is an unordered collection of unique values β duplicates are automatically dropped. Sets are the right tool whenever "does this already exist?" or "what do these two groups have in common?" matters more than order.
A comprehension is a compact way to build a new list, dictionary, or set by transforming every item from an existing one, in a single readable line, instead of writing a manual loop with append().
unique = {1, 2, 3}
squares = [x * x for x in numbers]
evens = [x for x in numbers if x % 2 == 0]
square_map = {x: x * x for x in numbers}Examples
Creating a set Very Easy
tags = {"python", "code", "python", "learn"}
print(tags)Duplicate 'python' is automatically removed β sets never contain repeated values. (Order in the printed output may vary.)
Set operations Easy
backend = {"python", "sql", "docker"}
frontend = {"javascript", "css", "python"}
print(backend & frontend)
print(backend | frontend)
print(backend - frontend)& is intersection (in both), | is union (in either), - is difference (in the first but not the second).
List comprehension Intermediate
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(squares)This replaces a 3-line append loop with one expressive line: 'give me x*x, for every x in numbers'.
Comprehension with a condition Real World
numbers = range(1, 11)
evens = [n for n in numbers if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(evens)
print(labels)A trailing if filters items; an if/else before the expression instead transforms every item differently based on a condition.
Dictionary comprehension Challenge
words = ["cat", "elephant", "dog"]
lengths = {word: len(word) for word in words}
print(lengths)The same {key: value for ...} pattern builds a dictionary instead of a list.
Visual Explanation
π‘ Why does this work?
Read the concept explanation above again slowly, line by line β every keyword there maps directly onto a line of code in the examples. If it still doesn't click, re-run the traced example (if this lesson has one) one step at a time.
π What happens internally? (advanced)
Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory β which is exactly what the memory panel in the tracer above is showing you.
Common Mistakes
Cramming too much logic into one comprehension hurts readability β if it doesn't fit on one clear line, a regular loop is better.
result = [y for y in [x*2 for x in range(20) if x % 3 == 0] if y > 10 if y < 30]doubled_multiples_of_3 = [x * 2 for x in range(20) if x % 3 == 0]
result = [y for y in doubled_multiples_of_3 if 10 < y < 30]- Reach for a comprehension when the loop body is a single, simple expression.
- Fall back to a normal for loop once a comprehension needs more than one condition or a nested loop.
- Use a set instead of a list when you need to guarantee uniqueness or check membership frequently β set lookups are much faster.
Exercise & Challenge
Exercise 1 β Predict the output
nums = [1, 2, 3, 4]
result = [n for n in nums if n > 2]
print(result)What does this print?
π Challenge
Given a list of words, use a dictionary comprehension to build a dictionary mapping each unique word to True if it starts with a vowel, and False otherwise.
- Use one dictionary comprehension
- Check the first letter with word[0].lower() in "aeiou"
- Test with at least 4 words
π‘ Need a hint?
{word: word[0].lower() in "aeiou" for word in words}
π Show a sample solution
words = ["apple", "banana", "orange", "kiwi"]
starts_with_vowel = {word: word[0].lower() in "aeiou" for word in words}
print(starts_with_vowel)Quiz
Answer every question, then submit to see your score and explanations.
1. What's special about the values inside a set?
2. What does the & operator do with two sets?
3. What does [x*x for x in range(3)] produce?
4. Which syntax builds a dictionary comprehension?
Summary
- Sets store unique, unordered values and support &, |, and - operations.
- List comprehensions build a new list from an existing iterable in one line.
- A trailing if filters; an if/else before the expression transforms conditionally.
- The same pattern extends to dictionary and set comprehensions with {}.