📘 Lesson 14 · Intermediate

Python Sets

Learn Python sets — unique unordered collections, union, intersection, difference with examples.

What is a Set?

A set is an unordered collection of unique values. It automatically removes duplicates, and elements have no fixed position. Sets use curly braces {} but don't have key-value pairs (that's a dict). The most common uses are removing duplicates from a list and fast membership testing — sets check x in s in O(1) constant time, much faster than lists.

create.py
fruits = {{"apple", "banana", "apple", "cherry"}}
print(fruits)        # "apple" only once

# Classic use: remove duplicates from a list
nums = [1, 2, 2, 3, 3, 4]
print(list(set(nums)))
▶ Output
{{'banana', 'apple', 'cherry'}}
[1, 2, 3, 4]

Adding and Removing

Use add() to add an element. Use discard() to remove safely — no error if the element doesn't exist. remove() also removes but raises a KeyError if the element is missing.

modify.py
s = {{1, 2, 3}}
s.add(4)
s.add(2)         # duplicate — silently ignored
print(s)
s.discard(3)     # safe remove
print(s)
▶ Output
{1, 2, 3, 4}
{1, 2, 4}

Set Operations

Sets support mathematical operations that are extremely useful in data work. Union (|) combines both. Intersection (&) finds items in both. Difference (-) finds items in the first but not the second. Symmetric difference (^) finds items in one but not both.

ops.py
a = {{1, 2, 3, 4}}
b = {{3, 4, 5, 6}}

print(a | b)   # union: all items
print(a & b)   # intersection: in BOTH
print(a - b)   # difference: in a, not b
print(a ^ b)   # symmetric diff: in one only
▶ Output
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}
Use a set instead of a list when order doesn't matter and you need fast duplicate removal or membership testing.

🧠 Quick Check

What happens when you add a duplicate value to a set?

Raises an error
Creates a second copy
Silently ignored
Replaces the set

Tags

setunionintersectiondifferencefrozensetadddiscard