PyComplete Python Course
Intermediate 45 min

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().

Syntax
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

Creating a set
tags = {"python", "code", "python", "learn"}
print(tags)
Output{'python', 'code', 'learn'}

Duplicate 'python' is automatically removed β€” sets never contain repeated values. (Order in the printed output may vary.)

Set operations Easy

Set operations
backend = {"python", "sql", "docker"}
frontend = {"javascript", "css", "python"}
print(backend & frontend)
print(backend | frontend)
print(backend - frontend)
Output{'python'} {'python', 'sql', 'docker', 'javascript', 'css'} {'sql', 'docker'}

& is intersection (in both), | is union (in either), - is difference (in the first but not the second).

List comprehension Intermediate

List comprehension
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(squares)
Output[1, 4, 9, 16, 25]

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

Comprehension with a condition
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)
Output[2, 4, 6, 8, 10] ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

A trailing if filters items; an if/else before the expression instead transforms every item differently based on a condition.

Dictionary comprehension Challenge

Dictionary comprehension
words = ["cat", "elephant", "dog"]
lengths = {word: len(word) for word in words}
print(lengths)
Output{'cat': 3, 'elephant': 8, 'dog': 3}

The same {key: value for ...} pattern builds a dictionary instead of a list.

Visual Explanation

x β†’ x * x112439416525
[x*x for x in numbers] transforms every input value into a new output value.
πŸ’‘ 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

βœ— Common mistake 1

Cramming too much logic into one comprehension hurts readability β€” if it doesn't fit on one clear line, a regular loop is better.

βœ— Avoid this
This raises not an error, but hard to read and debug
result = [y for y in [x*2 for x in range(20) if x % 3 == 0] if y > 10 if y < 30]
βœ“ Better approach
Fixed
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]
βœ“ Best practices
  • 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

Given this code
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
Python
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?

They must all be strings
They are automatically kept unique
They are always sorted
They can be changed by index
Sets automatically discard duplicate values.

2. What does the & operator do with two sets?

Union
Difference
Intersection
Symmetric difference
& returns items present in both sets.

3. What does [x*x for x in range(3)] produce?

[0, 1, 4]
[1, 4, 9]
[0, 1, 2]
SyntaxError
range(3) is 0,1,2; squaring gives 0,1,4.

4. Which syntax builds a dictionary comprehension?

[k: v for ...]
{k: v for ...}
(k: v for ...)
dict[k:v for ...]
Curly braces with a key:value pair define a dict 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 {}.

Related lessons

Saved privately in your browser β€” no account needed.