A set stores unique items with no order, like a bag of different marbles: you can drop one in or take one out, but you cannot ask for "the third marble", and a second marble of the same kind is never kept.
A set is unordered, mutable, holds only unique values, and every item must be hashable. The Set Methods index lists every guide, such as add(), discard(), and union().
Syntax
Python Syntax
Curly braces hold items separated by commas; in asks whether a value is in the set, and | joins two sets:
Python
fruits = {"apple", "banana", "cherry"} # a set literal
fruits.add("apple") # duplicates are ignored
print(len(fruits)) # 3
print("kiwi" in fruits) # False
print(sorted(fruits)) # ['apple', 'banana', 'cherry']
fruits.discard("banana") # remove one item
print(sorted(fruits | {"kiwi"})) # ['apple', 'cherry', 'kiwi']
for fruit in sorted(fruits):
print(fruit)
Order is never promised.
Printing a set or looping over it may show the items in any order, and for strings the order can change from one run to the next. When you need a stable result, use sorted(fruits), which returns a list in a fixed order. Every example on this page does that.
Concept
How Sets Behave
Rule
What it means
Unique items
Each value is stored once. Adding a value that is already there changes nothing, so {1, 1, 2} is the same set as {1, 2}.
Unordered
Items have no position: there is no s[0], and the order you see when printing or looping is not something you can rely on. Use sorted(s) for a fixed order.
Mutable
You can add and remove items after the set is created. Two names bound to the same set see the same changes.
Hashable items only
Numbers, strings, tuples of those, and frozenset can be items. A list, dict, or set cannot, and raises TypeError.
Fast membership
x in s is very quick even when the set is huge, which is why sets are good for "have I seen this?" checks.
Equal values collapse
1, 1.0, and True are equal, so a set keeps only the first one you add.
Reference
Creating Sets
Code
When to use it
{2, 3, 5, 7}
Literal: the most common way for a few known values.
set()
The only way to make an empty set, because {} is an empty dict.
set([4, 4, 9])
From any iterable; the repeated 4 is dropped. A quick way to remove duplicates.
set("hello")
A string gives one item per different character.
{n % 3 for n in nums}
Set comprehension: compute each item.
frozenset([1, 2])
An unchangeable set; it can be a set item or a dict key.
The set() constructor turns any iterable into a set and drops the duplicates, and frozenset() does the same for an unchangeable set. An empty set is always set(), never {}.
Reference
Set Math: Operators and Methods
Sets answer "what do these two groups have in common?" in one line. Each question has an operator and a method:
The operators need a set on both sides, while the methods also accept lists, tuples, and strings. Add _update to a method name, or put = after an operator, to change the set in place.
Reference
Common Mistakes
Mistake
Do this instead
s = {} for an empty set
That makes an empty dict. Write s = set() instead.
print(s) and expecting an order
A set has no order, and string items can print differently from run to run. Use print(sorted(s)).
x = s.add(1)
add() changes the set and returns None, so x is None. Call s.add(1) on its own line.
s.add([1, 2])
A list is unhashable and raises TypeError. Add a tuple, (1, 2), instead.
s[0]
A set has no positions, so this raises TypeError. Loop over the set, or use sorted(s)[0] for the smallest item.
remove() on a missing item
It raises KeyError. Use discard() when the item may be absent.
set("hello") to store a word
A string is split into its characters. Use {"hello"} or s.add("hello") to store the whole word.
Compare
Set vs List vs Tuple vs Dict
Type
Literal
Best for
Contents
Change it?
set
{1, 2}
Unique items, fast membership tests, set math
Unique, hashable items; no order
Mutable
list
[1, 2, 1]
Ordered items you will change
Duplicates allowed
Mutable
tuple
(1, 2, 1)
Fixed records, dict keys
Duplicates allowed
Immutable
dict
{"a": 1}
Look up values by key
Unique keys, insertion order
Mutable
Read more about ordered items on the Python List page and about key/value lookups on the Python Dict page.
Code
Python Examples
Fixed data only, and every set is printed with sorted(), so the output is the same on every machine.
Example 1 — Create Sets Five Different Ways
A literal, set() on a string and on a list with repeats, a set comprehension, and the empty set.
Union.| collects everyone from both clubs, and Cho and Dev are listed once even though they are in both.
Intersection and difference.& keeps the two shared students, while - keeps those only in the math club.
Symmetric difference.^ keeps students in exactly one club: Ana and Ben from math, and Eli from art.
Membership and subsets.in asks about one student, and <= asks whether the whole set {"Cho", "Dev"} fits inside the math club.
Example 3 — Hit Three Classic Set Mistakes on Purpose
Using {} for an empty set, adding a list, and storing the result of add().
Python
empty = {}
print(type(empty).__name__)
empty = set()
print(len(empty))
try:
bad = {[1, 2], 3}
except TypeError:
print("a list cannot be a set item")
result = empty.add(5)
print(result, empty)
Output
dict
0
a list cannot be a set item
None {5}
How It Works
{} is a dict. The first variable is an empty dictionary, and set() is the only way to get an empty set.
Only hashable items. A list can change, so putting [1, 2] inside a set literal raises TypeError; use a tuple (1, 2) instead.
add() returns None.add() changes the set and hands back nothing, so result is None and the set now holds 5.
A set is a built-in, unordered, mutable collection of unique, hashable items written in curly braces, such as {1, 2, 3}. It is ideal for removing duplicates and testing membership.
Use set(). Writing {} creates an empty dict, not an empty set.
A set has no order, and the layout depends on the hash values of its items, which can change between runs for strings. Use sorted(s) when you need a stable order.
Both delete an item and return None. If the item is missing, remove() raises KeyError, while discard() does nothing.
Use a set when you need unique items, quick membership tests, or set math such as union and intersection. Use a list when order or duplicates matter.