Skip to content

Python Sets

Unordered collections of unique elements: set operations, frozenset, and deduplication.

What you'll learn

  • Create sets and add/remove elements
  • Perform union, intersection, and difference
  • Use sets for deduplication and membership testing
  • Understand frozenset for immutable sets
  • Choose sets over lists for the right use cases

Concept

Creating Sets

A set is an unordered collection of unique elements. Duplicates are automatically removed:

empty = set()           # NOT {} — that creates a dict!
fruits = {"apple", "banana", "cherry"}
from_list = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

The most common way to create a set from existing data is set(iterable), which deduplicates automatically. Note that {} creates an empty dict, not an empty set — use set() for an empty set.

Adding and Removing

tags = {"python", "code"}

tags.add("learn")           # add one element
tags.update(["fun", "fast"]) # add multiple
tags.discard("code")        # remove if present (no error if missing)
tags.remove("python")       # remove — KeyError if missing
tags.pop()                  # remove and return an arbitrary element

Use .discard() when the element might not exist — it does not raise an error. .remove() raises KeyError if the element is absent.

Set Operations

Sets support mathematical operations using operators or methods:

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

# Union — elements in either
print(a | b)         # {1, 2, 3, 4, 5, 6}
print(a.union(b))    # same thing

# Intersection — elements in both
print(a & b)                # {3, 4}
print(a.intersection(b))    # same

# Difference — elements in a but not b
print(a - b)             # {1, 2}
print(a.difference(b))   # same

# Symmetric difference — elements in exactly one
print(a ^ b)                     # {1, 2, 5, 6}
print(a.symmetric_difference(b)) # same

# Subset and superset
print({1, 2}.issubset(a))   # True
print(a.issuperset({1, 2})) # True

The operator forms (| & - ^) are concise and readable. The method forms accept any iterable, not just sets.

Deduplication

The most common practical use of sets is removing duplicates from a list:

numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = list(set(numbers))  # [1, 2, 3, 4] (order not guaranteed)

Note: sets are unordered, so the order of the result is not guaranteed. If you need to preserve order while deduplicating, use dict.fromkeys() in Python 3.7+:

unique_ordered = list(dict.fromkeys(numbers))

Fast Membership Testing

Checking x in my_set is O(1) on average, while x in my_list is O(n). For large collections where you only test membership, a set is dramatically faster:

valid_ids = set(range(1_000_000))
print(500000 in valid_ids)  # instant — O(1)

frozenset

A frozenset is an immutable set — it cannot be modified after creation. Because it is hashable, it can be used as a dictionary key or an element of another set:

fs = frozenset([1, 2, 3])
# fs.add(4)  # AttributeError — immutable
d = {fs: "my frozen set"}  # valid — frozenset is hashable

When to Use Sets

  • Deduplication — remove duplicates from any iterable
  • Membership testing — fast in checks on large collections
  • Mathematical operations — union, intersection, difference
  • Removing items — when order does not matter and duplicates are unwanted

Example

              # Creating sets — duplicates removed automatically
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)  # {'apple', 'banana', 'cherry'}

from_list = set([1, 2, 2, 3, 3, 3])
print(from_list)  # {1, 2, 3}

# Adding and removing
tags = {"python", "code"}
tags.add("learn")
tags.update(["fun", "fast"])
tags.discard("missing")  # no error even if absent
print(tags)

# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)  # union: {1, 2, 3, 4, 5, 6}
print(a & b)  # intersection: {3, 4}
print(a - b)  # difference: {1, 2}
print(a ^ b)  # symmetric diff: {1, 2, 5, 6}

# Deduplication
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers))
print(unique)

# Order-preserving deduplication
unique_ordered = list(dict.fromkeys(numbers))
print(unique_ordered)  # [1, 2, 3, 4]

# Fast membership test
valid = set(range(1000))
print(500 in valid)  # True — O(1) lookup

# frozenset — immutable, hashable
fs = frozenset([1, 2, 3])
d = {fs: "frozen"}
print(d[fs])
            

Demonstrates set creation with automatic deduplication, add/update/discard, all four set operations (union, intersection, difference, symmetric difference), deduplication with and without order preservation, fast membership testing, and frozenset as a dict key.

Try it

  • Text Counter

    Counting unique words is a classic set use case.

  • JSON Formatter

    Sets serialize to JSON arrays — inspect unique values.

Common mistakes

The mistake

Using {} to create an empty set

The fix

{} creates an empty dict, not an empty set. Use set() to create an empty set. This is a very common beginner mistake — always use set() for empty sets.

The mistake

Expecting sets to preserve insertion order

The fix

Sets are unordered — iterating over a set does not guarantee any particular order. If you need order plus uniqueness, use dict.fromkeys() (Python 3.7+) or a list with manual deduplication.

Related Cheatsheets

Practice Python Sets

3 exercises

Practice Python Sets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors