The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Create a populated setcolors = {'red', 'green', 'blue'}View examples
Create an empty setvalues = set()View examples
Remove duplicatesunique = set(values)View examples
Test membershipif user_id in active_ids: allow()View examples
Add one membertags.add('python')View examples
Add several memberstags.update(['css', 'html'])View examples
Remove a required membertags.remove('legacy')View examples
Discard if presenttags.discard('legacy')View examples
Combine membersall_tags = required | optionalView examples
Keep shared membersshared = left & rightView examples
Subtract membersmissing = required - suppliedView examples
Keep non-shared memberschanged = before ^ afterView examples
Test subsetrequired <= suppliedView examples
Test proper subsetrequired < suppliedView examples
Test for no overlapleft.isdisjoint(right)View examples
Build with a comprehensionlengths = {len(word) for word in words}View examples
Create an immutable setpermissions = frozenset({'read', 'write'})View examples

A set stores distinct hashable objects and is optimized for membership tests and mathematical set operations. Sets are unordered, so never use their display or iteration order as a contract. Use frozenset when the collection itself must be hashable or immutable.

Step by step

Detailed examples

01

Create distinct collections explicitly

Set literals are concise for known values, while set(iterable) converts another collection and removes duplicates. Members must be hashable, so strings, numbers, tuples of hashable objects, and frozensets work; lists, dictionaries, and ordinary sets do not. Converting to a set discards order.

Deduplicate while treating order separately
colors = {'red', 'green', 'blue', 'red'}
empty = set()
unique_numbers = set([3, 1, 3, 2])

print(sorted(colors))
print(len(empty))
print(sorted(unique_numbers))
Output
['blue', 'green', 'red']
0
[1, 2, 3]
Back to quick reference ↑
02

Choose failure behavior when removing values

Membership tests express the central strength of a set. add and update mutate in place and return None. remove is useful when absence indicates a bug because it raises KeyError; discard is appropriate for idempotent cleanup. pop removes an arbitrary member, not the earliest or smallest one.

Update and clean a tag set
tags = {'python'}
tags.add('testing')
tags.update(['css', 'html', 'testing'])

print('python' in tags)
tags.discard('legacy')
tags.remove('css')
print(sorted(tags))
Output
True
['html', 'python', 'testing']
Back to quick reference ↑
03

Use operators for mathematical set results

Union, intersection, difference, and symmetric difference return new sets. Their named method forms can accept general iterables, while operators require set-like operands. In-place forms such as |= mutate the left operand, so use them only when callers do not depend on the original value.

Compare feature selections
before = {'search', 'export', 'alerts'}
after = {'search', 'sharing', 'alerts'}

print(sorted(before | after))
print(sorted(before & after))
print(sorted(before - after))
print(sorted(before ^ after))
Output
['alerts', 'export', 'search', 'sharing']
['alerts', 'search']
['export']
['export', 'sharing']
Back to quick reference ↑
04

Compare containment and overlap

<= and >= allow equality, while < and > require a proper subset or superset. These operators describe containment, not ordering: sets have no total order. isdisjoint can stop once it finds overlap and communicates intent better than building an intersection just to test whether it is empty.

Validate roles and conflicts
required = {'read'}
granted = {'read', 'write'}
forbidden = {'admin', 'owner'}

print(required <= granted)
print(required < granted)
print(granted.isdisjoint(forbidden))
Output
True
True
True
Back to quick reference ↑
05

Transform and filter into distinct results

A set comprehension has the same expression and filtering structure as a list comprehension but retains only distinct hashable results. It is useful when uniqueness is part of the result's meaning. If stable first-seen order matters, use dict.fromkeys(iterable) and convert only if set operations are later needed.

Normalize labels into unique values
labels = [' Python ', 'CSS', 'python', ' HTML ']
normalized = {label.strip().lower() for label in labels if label.strip()}
lengths = {len(label) for label in normalized}

print(sorted(normalized))
print(sorted(lengths))
Output
['css', 'html', 'python']
[3, 4, 6]
Back to quick reference ↑
06

Use frozenset for immutable set values

frozenset supports non-mutating set operations and membership but has no add, remove, or update methods. Because it is immutable and hashable when its members are hashable, it can be a dictionary key or a member of another set. This makes it useful for unordered composite identities.

Index routes by an unordered permission set
routes = {
    frozenset({'read'}): '/viewer',
    frozenset({'read', 'write'}): '/editor',
}
permissions = frozenset(['write', 'read'])

print(routes[permissions])
print(sorted(permissions | {'share'}))
Output
/editor
['read', 'share', 'write']
Back to quick reference ↑

Local code tester

Explore set relationships

Edit two collections and inspect their unique members, overlap, differences, and containment.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationBuilt-in Types: Set Typesdocs.python.org
  2. Python Software FoundationData Structures: Setsdocs.python.org
  3. Python Software FoundationSet displaysdocs.python.org
  4. Python Software FoundationHashable objectsdocs.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback