How to use sets

Create a set

Sets are mutable collections of unique hashable values. Use set(), not {}, for an empty set because empty braces create a dictionary.

tags = {"python", "beginner", "python"}
empty = set()
print(tags)
print(type(empty))

Add, remove, and test

Membership tests are typically fast. discard() does nothing when an item is absent, whereas remove() raises KeyError.

users = {"ada", "grace"}
users.add("linus")
users.discard("missing")
print("ada" in users)
print(users)

Combine sets

Union combines values, intersection keeps shared values, and difference keeps values found only on the left.

python_students = {'Ada', 'Sam', 'Lee'}
web_students = {'Sam', 'Kim'}
print(python_students | web_students)
print(python_students & web_students)
print(python_students - web_students)

Remove duplicates

Converting a list to a set removes duplicates. Sort the result when output order matters.

numbers = [3, 1, 3, 2, 1]
unique_sorted = sorted(set(numbers))
print(unique_sorted)