Built-in function

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.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
iterable
optional, 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

Pythoneditable
visits = ["Rome", "Paris", "Rome", "Oslo", "Paris", "Rome"]
unique = set(visits)
print(len(visits), "visits,", len(unique), "cities")
print(sorted(unique))
Output
6 visits, 3 cities
['Oslo', 'Paris', 'Rome']

We print sorted(unique) because the set's own order is not fixed.

2Compare two groups

Pythoneditable
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))
Output
Both days: ['Ben', 'Dara']
Either day: ['Ana', 'Ben', 'Chen', 'Dara', 'Eli']
Only Monday: ['Ana', 'Chen']

3The letters used in a word

Pythoneditable
letters = set("bookkeeper")
print(len(letters))
print(sorted(letters))
print("".join(sorted(letters)))
Output
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

Pythoneditable
print(type({}))
print(type(set()))
empty = set()
empty.add("first")
print(empty)
Output
<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:

Pythoneditable
emails = ["b@mail.test", "a@mail.test", "b@mail.test", "c@mail.test"]
print(list(dict.fromkeys(emails)))
Output
['b@mail.test', 'a@mail.test', 'c@mail.test']

Common mistakes

Writing {} for an empty set

{} makes a dictionary, so .add() fails on it. Use set().

Pythoneditable
seen = {}
try:
    seen.add("x")
except AttributeError:
    print("AttributeError: a dict has no add()")
seen = set()
seen.add("x")
print(seen)
Output
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"}.

Pythoneditable
print(sorted(set("apple")))
print({"apple"})
Output
['a', 'e', 'l', 'p']
{'apple'}

Putting lists inside a set

Set items must be unchangeable. A list raises TypeError; use a tuple instead.

Pythoneditable
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))
Output
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.

Spotted a mistake on this page? Tell us