set()
Builds a set, a collection where every item appears only once: the quick way to remove duplicates and to find what two groups share.
set(iterable=())set() collects items into a set: an unordered collection with no duplicates. set([3, 1, 3, 2, 1]) keeps just 1, 2 and 3.
Sets are ideal for three jobs: removing duplicates, checking quickly whether something is present (x in s stays fast even with millions of items), and comparing groups with & (in both), | (in either) and - (in one but not the other).
Two surprises. First, {} is an empty dictionary, not an empty set; write set() for that. Second, a set has no order: the same set of words may print in a different order on another run or computer. Sort it with sorted() whenever you show it.
Parameters
| Parameter | What it is |
|---|---|
iterableoptional, default () | Anything you can loop over. Its items must be hashable (unchangeable values such as numbers, strings and tuples; not lists). With nothing, you get an empty set. |
Return value
A new set.
Examples
1Remove duplicates
visits = ["Rome", "Paris", "Rome", "Oslo", "Paris", "Rome"]
unique = set(visits)
print(len(visits), "visits,", len(unique), "cities")
print(sorted(unique))6 visits, 3 cities ['Oslo', 'Paris', 'Rome']
We print sorted(unique) because the set's own order is not fixed.
2Compare two groups
monday = set(["Ana", "Ben", "Chen", "Dara"])
tuesday = set(["Ben", "Dara", "Eli"])
print("Both days:", sorted(monday & tuesday))
print("Either day:", sorted(monday | tuesday))
print("Only Monday:", sorted(monday - tuesday))Both days: ['Ben', 'Dara'] Either day: ['Ana', 'Ben', 'Chen', 'Dara', 'Eli'] Only Monday: ['Ana', 'Chen']
3The letters used in a word
letters = set("bookkeeper")
print(len(letters))
print(sorted(letters))
print("".join(sorted(letters)))6 ['b', 'e', 'k', 'o', 'p', 'r'] bekopr
"bookkeeper" has 10 letters but only 6 different ones. Passing a string to set() splits it into characters.
4Empty set vs empty dictionary
print(type({}))
print(type(set()))
empty = set()
empty.add("first")
print(empty)<class 'dict'>
<class 'set'>
{'first'}5Remove duplicates but keep the order
A set forgets the order. If the order matters, use a dictionary's keys instead, which keep it:
emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
print(list(dict.fromkeys(emails)))['[email protected]', '[email protected]', '[email protected]']
Common mistakes
Writing {} for an empty set
{} makes a dictionary, so .add() fails on it. Use set().
seen = {}
try:
seen.add("x")
except AttributeError:
print("AttributeError: a dict has no add()")
seen = set()
seen.add("x")
print(seen)AttributeError: a dict has no add()
{'x'}Passing one string to set()
set("apple") splits the word into letters. For a set that holds the whole word, use braces: {"apple"}.
print(sorted(set("apple")))
print({"apple"})['a', 'e', 'l', 'p']
{'apple'}Putting lists inside a set
Set items must be unchangeable. A list raises TypeError; use a tuple instead.
try:
points = set([[1, 2], [3, 4]])
except TypeError:
print("TypeError: lists cannot go in a set")
points = set([(1, 2), (3, 4), (1, 2)])
print(sorted(points))TypeError: lists cannot go in a set [(1, 2), (3, 4)]
Questions people ask
How do I remove duplicates from a list in Python?
list(set(items)) if the order does not matter; list(dict.fromkeys(items)) to keep the first-seen order.
Why does my set print in a different order?
Sets are not ordered. The order you see depends on internal details and can change between runs. Use sorted(my_set) when order matters.
How do I create an empty set?
set(). The literal {} is an empty dictionary.
Why use a set instead of a list for in checks?
A set finds an item almost instantly; a list has to look through every element. With large data the difference is huge.