Python Sets
A set is an unordered collection of unique items, useful for membership tests and removing duplicates.
What is a set?
A set stores a group of values with two key rules: every item must be unique, and the items have no fixed order. Because there is no order, sets do not support indexing or slicing, but they are extremely fast at answering the question "is this value already here?" Sets are ideal for tasks like removing duplicates or comparing groups of data.
You create a set by placing comma-separated values inside curly braces. If you list the same value more than once, Python keeps only a single copy.
Creating a set
colors = {"red", "green", "blue"}
print(colors)
# Duplicates are automatically dropped
nums = {1, 2, 2, 3, 3, 3}
print(nums) # {1, 2, 3}
print(len(nums)) # 3Set characteristics
- Unordered: items have no index and no guaranteed position.
- Unique: duplicate values are automatically removed.
- Unindexed: you cannot access items by position.
- Items must be immutable (numbers, strings, tuples), so a set cannot contain a list.
- The set itself is changeable: you can add and remove items.
Membership and looping
Since you cannot use an index, you access set data by checking membership with the in keyword or by looping through the items. Membership tests on a set are typically much faster than the same test on a list.
Testing and looping
permissions = {"read", "write", "execute"}
if "write" in permissions:
print("Write access granted")
for p in permissions:
print(p)A common use: removing duplicates
Converting a list to a set and back is a quick idiom for stripping out duplicate values, though the original order is not preserved.
Deduplicating a list
names = ["Ann", "Bob", "Ann", "Cara", "Bob"]
unique = list(set(names))
print(unique) # e.g. ['Bob', 'Cara', 'Ann']Exercise: Python Sets
What happens when you add a duplicate value to a Python set?