A set is a collection of unique, unordered values. If you add the same value twice, only one is kept. It is the perfect structure to remove repeats and to quickly check whether a value is present or not.
Creating sets
colors = {"red", "green", "blue"}
numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3}
print(len(numbers)) # 3
To create an empty set you must use set(). Empty braces {} create a dictionary, not a set:
empty = set()
print(type(empty)) # <class 'set'>
print(type({})) # <class 'dict'>
You can also convert another collection into a set with set():
print(set([4, 2, 4, 2, 7])) # {2, 4, 7}
print(set("abracadabra")) # a set with the letters a, b, r, c, d
No order and no indexes
The elements of a set have no position: there is no my_set[0] and the order in which they are displayed may vary. If you need to see them sorted, use sorted(), which returns a list:
letters = set("hello world")
print(sorted(letters))
# [' ', 'd', 'e', 'h', 'l', 'o', 'r', 'w']
Adding and removing elements
fruits = {"apple", "pear"}
fruits.add("grape") # adds an element
fruits.add("pear") # already there: nothing changes
fruits.remove("apple") # removes; KeyError if it does not exist
fruits.discard("kiwi") # removes if present; otherwise does nothing
print(sorted(fruits)) # ['grape', 'pear']
Checking whether a value is present
The in operator is very fast on a set, even with millions of elements, because it does not go through all the values one by one:
seen = {3, 7, 9}
print(7 in seen) # True
print(8 in seen) # False
print(8 not in seen) # True
Looping over a set
for number in sorted({5, 1, 3}):
print(number)
# 1
# 3
# 5
Removing duplicates from a list
The most common use of a set is removing repeats:
data = [4, 2, 4, 2, 7, 1]
unique = sorted(set(data))
print(unique) # [1, 2, 4, 7]
Counting how many distinct values there are is as simple as len(set(data)).
Practice in Remove duplicates and Distinct letters.