Programmer's Picnic · Python Foundations · 0 → ∞

Python Sets: From 0 to Infinity

Remove duplicates and solve membership and comparison problems with set algebra.

Free course · 55–75 minutes reading and practice · No installation beyond Python 3

How to learn

Read one level, type the code into the editor, predict the output, then run it. Change one line and observe the result before proceeding. All code examples work with standard Python 3 (the dictionary union example requires 3.9 or newer).

The course moves from first principles to realistic code, common mistakes, performance and a mini-project.

Level 0 / 10

0 · A set stores unique values

A set is a mutable, unordered collection of distinct hashable elements. Display order is not guaranteed.

Python 3 · runnable example
numbers = {2, 3, 2, 5}
print(len(numbers))
print(3 in numbers)
print(type(numbers).__name__)
Expected output
3
True
set

Remember: Do not assume the order printed by a set; use sorted() for a predictable display.

Level 1 / 10

1 · Creating an empty set

{} makes an empty dictionary, not a set. Write set(). Convert an iterable to a set to discard duplicates.

Python 3 · runnable example
empty = set()
unique = set([4, 4, 2, 1])
print(type(empty).__name__)
print(sorted(unique))
Expected output
set
[1, 2, 4]

Remember: Converting to a set does not retain original order. dict.fromkeys(items) can deduplicate while preserving order.

Level 2 / 10

2 · Adding and removing

add() inserts one value; update() inserts from an iterable; discard() is safe for absent members, whereas remove() raises KeyError.

Python 3 · runnable example
skills = {'Python'}
skills.add('SQL')
skills.update(['HTML', 'CSS'])
skills.discard('Java')
print(sorted(skills))
Expected output
['CSS', 'HTML', 'Python', 'SQL']

Remember: pop() removes an arbitrary element; do not use it to retrieve a supposed first member.

Level 3 / 10

3 · Union and intersection

Union collects all distinct members. Intersection keeps only members shared by both sets. Operators | and & provide concise syntax.

Python 3 · runnable example
a = {'Python', 'SQL'}
b = {'SQL', 'Java'}
print(sorted(a | b))
print(sorted(a & b))
Expected output
['Java', 'Python', 'SQL']
['SQL']

Remember: a.union(b) and a.intersection(b) have the same meanings as | and &.

Level 4 / 10

4 · Difference and symmetric difference

Difference a-b keeps members only in a. Symmetric difference a^b keeps members in exactly one of the sets.

Python 3 · runnable example
a = {1, 2, 3}
b = {3, 4}
print(sorted(a - b))
print(sorted(b - a))
print(sorted(a ^ b))
Expected output
[1, 2]
[4]
[1, 2, 4]

Remember: Difference is directional: a-b is generally not the same as b-a.

Level 5 / 10

5 · Subsets and disjoint sets

A <= B checks whether A is a subset of B. isdisjoint() checks whether two sets share no elements.

Python 3 · runnable example
required = {'HTML', 'CSS'}
student = {'HTML', 'CSS', 'Python'}
print(required <= student)
print(required < student)
print(required.isdisjoint({'SQL'}))
Expected output
True
True
True

Remember: < tests a proper subset; <= allows equality.

Level 6 / 10

6 · Set comprehensions

Like list comprehensions, set comprehensions transform and filter values but produce unique results.

Python 3 · runnable example
words = ['cat', 'dog', 'cat', 'owl']
lengths = {len(word) for word in words}
initials = {word[0] for word in words}
print(sorted(lengths))
print(sorted(initials))
Expected output
[3]
['c', 'd', 'o']

Remember: Use generator expressions if you do not need to store the complete set.

Level 7 / 10

7 · Hashability and nested data

Set members must be hashable: numbers, strings and tuples of hashable members work; lists and dictionaries do not.

Python 3 · runnable example
coordinates = {(2, 3), (4, 5), (2, 3)}
print(len(coordinates))
print((4, 5) in coordinates)
Expected output
2
True

Remember: A tuple containing an unhashable list is also unhashable.

Level 8 / 10

8 · frozenset for immutable sets

frozenset cannot be modified after creation and can be used as a dictionary key if its elements are hashable.

Python 3 · runnable example
pair = frozenset({'Asha', 'Meera'})
team_scores = {pair: 10}
print(team_scores[frozenset({'Meera', 'Asha'})])
Expected output
10

Remember: A frozenset has no add() or remove() methods.

Level 9 / 10

9 · Efficiency and order pitfalls

Average-case membership tests are O(1), although pathological hashing can degrade performance. A set has no meaningful position, so never index or slice it.

Python 3 · runnable example
seen = set()
for code in ['A', 'B', 'A', 'C']:
    if code not in seen:
        seen.add(code)
        print('New:', code)
Expected output
New: A
New: B
New: C

Remember: The example prints in input order because we iterate a list, not because sets are ordered.

Level 10 / 10

10 · Mini-project: club comparison

Find students who belong to both clubs, just one club, or all clubs combined.

Python 3 · runnable example
coding = {'Asha', 'Ravi', 'Meera'}
robotics = {'Meera', 'Kabir'}
print('Both:', sorted(coding & robotics))
print('Only coding:', sorted(coding - robotics))
print('Either:', sorted(coding | robotics))
Expected output
Both: ['Meera']
Only coding: ['Asha', 'Ravi']
Either: ['Asha', 'Kabir', 'Meera', 'Ravi']

Remember: Extension: show students in exactly one of the clubs with coding ^ robotics.

Practice lab

Test your understanding

Predict or explain the answer before opening the solution. Try rewriting one of the examples without copying it.

1. What is the result of type({}).__name__?

Answer: dict

Use set() for an empty set.

2. Which operation finds common elements?

Answer: a & b or a.intersection(b)

Intersection is the overlap.

3. Can you use my_set[0]?

Answer: No; sets have no positional indexing.

Sort when you need a predictable sequence.

Take it further: expand the mini-project with an input() prompt, a reusable function, input validation and three tests (normal, empty and boundary cases).

When to use each Python collection

Comparison of Python built-in data types
TypeOrdered?Mutable?Duplicates?Best for
strYesNoYesText
listYesYesYesChanging sequences
tupleYesNo*YesFixed records
setNo guaranteed orderYesNoUnique membership
dictInsertion orderYesKeys uniqueNamed lookups

* A tuple itself cannot be reassigned, but a mutable item stored inside it can still change.

Python official built-in types reference ↗

Programmer's Picnic · Developed and maintained by Champak Roy · Practice with real Python, one step at a time.