Python 3 reference · Built-in Functions
Python set() Function
Create a set: an unordered collection of unique items with fast membership tests and set operations.
Python 3 Since 3.0
Syntax
set(iterable=())
Parameters
| Parameter | Description |
|---|---|
iterable optional |
Items for the set; duplicates are dropped. |
Return value
A new set.
Examples
print(sorted(set([3, 1, 3, 2, 1])))
print(set()) # the empty set ({} is an empty dict!)
Output
[1, 2, 3] set()
python = {"Ada", "Linus", "Grace"}
rust = {"Linus", "Ken"}
print(sorted(python & rust)) # in both
print(sorted(python | rust)) # in either
print(sorted(python - rust)) # only in python
Output
['Linus'] ['Ada', 'Grace', 'Ken', 'Linus'] ['Ada', 'Grace']
allowed = set("abcdef")
print(all(c in allowed for c in "cafe"), "z" in allowed)
Output
True False
Common mistakes
{}creates an empty dict; useset()for an empty set.- Sets have no order:
set([3, 1, 2])may print in any order. Sort it for stable output. - Items must be hashable: a set can contain tuples but not lists.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
frozenset()· Create an immutable set: unique items that can't be added or removed, so it is hashable and can be a dict key.list()· Create a list: an ordered, changeable sequence. Called with an iterable, it copies its items into a new list.dict()· Create a dictionary: a mapping of keys to values. Build it from keyword arguments, pairs or another mapping.sorted()· Return a new sorted list from any iterable. Supports a key function and reverse order; the original is left unchanged.- Python Sets · tutorial