← Back to Python Course | Chapter 6: Data Structures | Lesson 4 of 12

Python Sets

What is a Set?

A set stores unique, unordered elements -- adding a duplicate silently does nothing -- and because sets use hashing internally, membership checks are much faster than scanning a list. Curly braces {} define a set, but an empty {} actually creates a dict, so use set() for an empty one.

Example: What is a Set?

python
numbers = {1, 2, 2, 3}
print(numbers)
empty = set()
print(type(empty))

Adding and Removing Items

add(item) inserts a single new element (no effect if it's already present), remove(item) deletes it but raises KeyError if missing, and discard(item) does the same removal without raising an error -- discard() is the safer choice when you're not sure the item is there.

Example: Adding and Removing Items

python
s = {1, 2, 3}
s.add(4)
s.discard(10)
print(s)

Union and Intersection

union() (or the | operator) returns a new set containing every element from both sets with duplicates automatically collapsed, which is the set-theory equivalent of combining two guest lists into one without repeats.

Example: Union and Intersection

python
a = {1, 2, 3}
b = {2, 3, 4}
print(a.union(b))
print(a.intersection(b))

Set Difference

difference() (or -) returns elements in the first set that aren't in the second, useful for finding whats in A but missing from B'; symmetric_difference() (or ^) returns elements that are in exactly one of the two sets, not both.

Example: Set Difference

python
a = {1, 2, 3}
b = {2, 3, 4}
print(a.difference(b))
print(a.symmetric_difference(b))

Set Membership and Checking

in checks membership just like it does for lists, but on a set it runs in roughly constant time regardless of size; issubset() checks whether every element of one set also appears in another, which is handy for permission or capability checks.

Example: Set Membership and Checking

python
a = {1, 2}
b = {1, 2, 3}
print(1 in b)
print(a.issubset(b))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.