Free Python Set Methods Cheat Sheet Online — Interactive Reference with Examples

·

Try the tool first:

Open the Interactive Python Set Methods Cheat Sheet

40+ methods, real-time search, category filtering, one-click copy. 100% client-side, no signup.

Python sets are one of the most underutilized built-in data structures. Every element is unique, membership tests are O(1), and set operations mirror the mathematical concepts you learned in school. Yet even experienced developers occasionally pause: Is union() the same as |? When do I use frozenset? What's the difference between remove() and discard()? How do I deduplicate a list and preserve order?

This comprehensive guide covers every Python set method, operator, and common pattern you need to know. Each section includes practical code examples you can copy and run immediately. By the end, you'll know sets inside and out — and you'll have a free interactive cheat sheet bookmarked for quick reference.

What Are Python Sets?

A Python set is an unordered collection of unique, hashable elements. Sets are implemented as hash tables in CPython, giving them O(1) average-case time complexity for membership tests, insertions, and deletions. They are defined with the set() constructor or curly braces containing elements.

# Creating sets
empty = set()           # Empty set (must use set(), not {})
numbers = {1, 2, 3, 4, 5}

# From an iterable
from_list = set([1, 2, 2, 3, 3, 3])   # {1, 2, 3}
from_string = set("hello")            # {'h', 'e', 'l', 'o'}

# Set comprehension
squares = {x**2 for x in range(10)}   # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

# Important: {} creates an empty dict, not a set!
empty_dict = {}         # dict
empty_set = set()       # set

Key Characteristics

  • Unordered: Elements have no index. You cannot access them by position.
  • Unique: Duplicate elements are automatically removed.
  • Mutable: You can add and remove elements after creation (unlike frozenset).
  • Hashable elements only: Lists and dictionaries cannot be set elements.

Performance note: Set membership testing (elem in s) is O(1) on average. For a list, it's O(n). If you need to test membership repeatedly on a large collection, convert it to a set first.

Creating Sets

Literal Syntax

Use curly braces with comma-separated elements. Remember: creates a dictionary, not a set.

fruits = {"apple", "banana", "cherry"}
mixed = {1, "two", 3.0, (4, 5)}       # All elements must be hashable

# Invalid — unhashable types
# bad = {[1, 2], {"a": 1}}            # TypeError

set() Constructor

The set() constructor accepts any iterable and removes duplicates automatically.

# From list (deduplicates)
numbers = set([1, 2, 2, 3, 3, 3])     # {1, 2, 3}

# From tuple
letters = set(("a", "b", "c"))        # {'a', 'b', 'c'}

# From string (each character becomes an element)
chars = set("mississippi")            # {'m', 'i', 's', 'p'}

# From range
r = set(range(5))                     # {0, 1, 2, 3, 4}

# From dict (keys only)
d = {"a": 1, "b": 2}
keys = set(d)                         # {'a', 'b'}

Set Comprehensions

Set comprehensions provide a concise way to create sets, similar to list comprehensions.

# Basic set comprehension
squares = {x**2 for x in range(10)}

# With condition
evens = {x for x in range(20) if x % 2 == 0}

# From nested data
matrix = [[1, 2], [2, 3], [3, 4]]
flat = {x for row in matrix for x in row}   # {1, 2, 3, 4}

# Remove duplicates while transforming
words = ["Apple", "Banana", "apple", "banana"]
lower_unique = {w.lower() for w in words}   # {'apple', 'banana'}

frozenset() — Immutable Sets

A frozenset is an immutable version of a set. Once created, it cannot be modified. Because it is hashable, it can be used as a dictionary key or as an element in another set.

fs = frozenset([1, 2, 3])

# frozenset supports all non-mutating methods:
fs2 = fs.union({3, 4, 5})             # frozenset({1, 2, 3, 4, 5})
fs3 = fs.intersection({2, 3, 4})      # frozenset({2, 3})

# But not mutating methods:
# fs.add(4)                             # AttributeError!

# Use case: sets as dict keys
scores = {
    frozenset({"Alice", "Bob"}): 10,
    frozenset({"Carol", "Dave"}): 20,
}

# Use case: set of sets
unique_groups = {frozenset({1, 2}), frozenset({2, 3})}

Adding and Removing Elements

add() — Add a Single Element

s.add(elem) inserts a single element into the set. If the element already exists, the set is unchanged (no error). This is an in-place operation.

s = {1, 2, 3}
s.add(4)              # {1, 2, 3, 4}
s.add(2)              # {1, 2, 3, 4} — no error, no change

# Time complexity: O(1) average

update() / |= — Add Multiple Elements

s.update(iterable) adds all elements from an iterable to the set. The |= operator does the same thing and is available in Python 3.7+.

s = {1, 2, 3}
s.update([3, 4, 5])   # {1, 2, 3, 4, 5}

# Equivalent with |= operator
s |= {6, 7}           # {1, 2, 3, 4, 5, 6, 7}

# Multiple iterables at once
s.update([8, 9], (10, 11), {"a", "b"})

remove() — Remove with Error

s.remove(elem) removes the element. If it does not exist, it raises a KeyError. Use this when you expect the element to be present (fail fast).

s = {1, 2, 3}
s.remove(2)           # {1, 3}

# s.remove(99)        # KeyError: 99

# Safe pattern:
if 99 in s:
    s.remove(99)

discard() — Remove Without Error

s.discard(elem) removes the element if it exists. If not, it does nothing. This is the safer default for most cases.

s = {1, 2, 3}
s.discard(2)          # {1, 3}
s.discard(99)         # No error, set unchanged

# Preferred over remove() unless you need KeyError as control flow

pop() — Remove and Return Arbitrary Element

s.pop() removes and returns an arbitrary element from the set. Because sets are unordered, you cannot predict which element will be removed. Raises KeyError if the set is empty.

s = {1, 2, 3}
item = s.pop()        # item is 1, 2, or 3 — unpredictable

# Empty set
empty = set()
# empty.pop()         # KeyError

Rule of thumb: Use add() for single elements, update() or |= for multiple. Use discard() as your default removal method. Use remove() only when the element must exist. Use pop() only when you need to consume elements one by one and don't care which.

Set Operations

Python sets support the full range of mathematical set operations. Each operation has two forms: a method that returns a new set, and an in-place method that modifies the original.

Union — All Elements from Both Sets

The union contains all elements that are in either set.

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

# Method
a.union(b)            # {1, 2, 3, 4, 5}

# Operator
a | b                 # {1, 2, 3, 4, 5}

# Multiple sets
a | b | {6, 7}        # {1, 2, 3, 4, 5, 6, 7}

# In-place (modifies a)
a.update(b)
a |= b

Intersection — Elements Common to Both Sets

The intersection contains only elements that are in both sets.

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

a.intersection(b)     # {2, 3}
a & b                 # {2, 3}

# In-place
a.intersection_update(b)
a &= b

Difference — Elements in A but Not in B

The difference contains elements that are in the first set but not in the second.

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

a.difference(b)       # {1}
a - b                 # {1}

# Note: difference is NOT commutative!
b - a                 # {4}

# In-place
a.difference_update(b)
a -= b

Symmetric Difference — Elements in Either Set, But Not Both

The symmetric difference contains elements that are in exactly one of the sets. It is the XOR of sets.

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

a.symmetric_difference(b)   # {1, 4}
a ^ b                       # {1, 4}

# In-place
a.symmetric_difference_update(b)
a ^= b

Disjoint — No Elements in Common

s.isdisjoint(other) returns True if the two sets have no elements in common.

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

a.isdisjoint(b)       # True
a.isdisjoint(c)       # False

Querying and Inspecting

Membership Testing

Sets are optimized for membership testing. The in and not in operators average O(1) time.

s = {1, 2, 3, 4, 5}

1 in s                # True
99 in s               # False
99 not in s           # True

# Much faster than list for large collections

Length

len(s) returns the number of unique elements in the set.

s = {1, 2, 2, 3}
len(s)                # 3 (duplicates removed)

Subset and Superset

Test whether one set is contained within another.

a = {1, 2}
b = {1, 2, 3}

a.issubset(b)         # True
a <= b                # True

b.issuperset(a)       # True
b >= a                # True

# Proper subset (strict)
a < b                 # True (a is subset and a != b)
a < a                 # False

# Proper superset (strict)
b > a                 # True
b > b                 # False

Copying and Clearing

copy() — Shallow Copy

s.copy() returns a shallow copy of the set. Equivalent to set(s).

s = {1, 2, 3}
t = s.copy()
t.add(4)
# s is still {1, 2, 3}
# t is {1, 2, 3, 4}

clear() — Remove All Elements

s.clear() removes all elements, leaving an empty set.

s = {1, 2, 3}
s.clear()
# s is now set()

Comparison Tables

Union Methods

MethodReturnsMutates?ExampleWhen to Use
s.union(other)New setNoa.union(b)Functional style, method chaining
s | otherNew setNoa | bOperator style, multiple operands
s.update(other)NoneYesa.update(b)Add elements to existing set
s |= otherNoneYesa |= bConcise in-place union

Intersection Methods

MethodReturnsMutates?ExampleWhen to Use
s.intersection(other)New setNoa.intersection(b)Keep only shared elements in new set
s & otherNew setNoa & bOperator style
s.intersection_update(other)NoneYesa.intersection_update(b)Keep only shared elements in-place
s &= otherNoneYesa &= bConcise in-place intersection

Difference Methods

MethodReturnsMutates?ExampleWhen to Use
s.difference(other)New setNoa.difference(b)Elements in a but not b
s - otherNew setNoa - bOperator style
s.difference_update(other)NoneYesa.difference_update(b)Remove b elements from a
s -= otherNoneYesa -= bConcise in-place difference

Symmetric Difference Methods

MethodReturnsMutates?ExampleWhen to Use
s.symmetric_difference(other)New setNoa.symmetric_difference(b)Elements in exactly one set
s ^ otherNew setNoa ^ bOperator style
s.symmetric_difference_update(other)NoneYesa.symmetric_difference_update(b)In-place symmetric difference
s ^= otherNoneYesa ^= bConcise in-place

Performance Complexity

OperationAverage TimeWorst TimeNotes
add(x)O(1)O(n)Hash table insertion
remove(x)O(1)O(n)Hash table deletion
discard(x)O(1)O(n)Same as remove
pop()O(1)O(n)Removes arbitrary element
x in sO(1)O(n)Hash table lookup
len(s)O(1)O(1)Stored internally
union (|)O(len(s)+len(t))O(len(s)+len(t))Iterate both sets
intersection (&)O(min(len(s), len(t)))O(len(s) * len(t))Iterate smaller set
difference (-)O(len(s))O(len(s) * len(t))Iterate s, check t
copy()O(len(s))O(len(s))Shallow copy
clear()O(1)O(1)Drop reference

Common Patterns

Deduplicate a List

The classic use case for sets. Note that order is lost.

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

# Preserve order (Python 3.7+)
unique_ordered = list(dict.fromkeys(items))

Find Unique Elements in One List vs Another

a = ["apple", "banana", "cherry"]
b = ["banana", "cherry", "date"]

only_in_a = set(a) - set(b)     # {'apple'}
only_in_b = set(b) - set(a)     # {'date'}
in_both = set(a) & set(b)       # {'banana', 'cherry'}

Count Unique Items

words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
unique_count = len(set(words))  # 3

Remove Seen Elements While Iterating

items = [1, 2, 2, 3, 3, 3, 4]
seen = set()
result = []
for x in items:
    if x not in seen:
        seen.add(x)
        result.append(x)
# result → [1, 2, 3, 4]

Filter with Set for Speed

whitelist = {"python", "javascript", "rust", "go"}
tags = ["python", "java", "rust", "csharp", "go"]

# O(len(tags)) — fast!
valid = [t for t in tags if t in whitelist]
# ['python', 'rust', 'go']

Set vs List vs Dictionary

FeatureListSetDict
OrderedYesNoYes (3.7+)
DuplicatesAllowedRemovedKeys unique
LookupO(n)O(1)O(1)
IndexedYesNoBy key
MutableYesYesYes
HashableNoNoNo

Pro Tips and Gotchas

Gotcha: is a dict, not a set. The empty set must be created with set(). always creates an empty dictionary. If you write s = , you have a dict.

Tip: Prefer discard() over remove(). Unless you are using KeyError as intentional control flow, discard() is safer and produces cleaner code. It does the same thing without raising exceptions.

Tip: Use frozenset for hashable sets. If you need a set as a dictionary key, or a set containing other sets, use frozenset. It supports all read-only operations and is fully hashable.

Performance tip: For large collections, convert to a set before repeated membership testing. A single set() call costing O(n) can save thousands of O(n) list scans later.

Tip: Set comprehensions are fast. Just like list comprehensions, set comprehensions are generally faster and more readable than equivalent for-loops. Use them whenever you are building a set from an iterable.

Found this useful? Check out our free developer tools or browse more articles.