Python Sets: Unique Items, add(), remove() and in
What Is a Set in Python?
A set is a collection where every item appears only once, written in curly brackets: {"red", "blue"}. A set has no order and no positions.
colors = {"red", "blue", "red", "green", "blue"}
print(len(colors))
print("red" in colors)
print(sorted(colors))3 True ['blue', 'green', 'red']
Five colors went in, but the set kept only three: the repeated "red" and "blue" were dropped by themselves.
Think of it like the guest list for a party. Writing Sunny's name twice doesn't bring two Sunnys. And nobody on the list is "guest number 1": it's only about who is on it.
The rules
- Items go inside curly brackets, separated by commas.
- A set never holds the same item twice. Duplicates are dropped, with no error.
- A set has no order, so there are no indexes: no
colors[0]. len(),inand a for loop all work.- An empty set is
set(). Empty curly brackets{}make an empty dictionary (chapter 13).
Show a set with sorted()
Python keeps the items of a set in its own order. That order can look random, and it can even be different on another computer. So when you want to show a set, sort it first: sorted() gives back a list in order, the same every time. You'll see sorted() around every set in this chapter.
Avoid: an index
colors = {"red", "blue"}
print(colors[0])TypeError: 'set' object is not subscriptable
Don't be scared of the long word! "Subscriptable" means "you can use [] on it". A set has no first item, so [0] means nothing. Ask with in instead: "red" in colors.
Avoid: {} for an empty set
a = {}
b = set()
print(type(a))
print(type(b))<class 'dict'> <class 'set'>
Common beginner doubt: "Curly brackets? Isn't that a dictionary?" Both use them. A dictionary holds key: value pairs, with a colon. A set holds single items, with no colons.
A set keeps each item once and has no order. Show it in order with sorted().