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

ParameterDescription
iterable optional Items for the set; duplicates are dropped.

Return value

A new set.

Examples

Remove duplicatesTry it yourself
print(sorted(set([3, 1, 3, 2, 1])))
print(set())  # the empty set ({} is an empty dict!)

Output

[1, 2, 3]
set()
Set operationsTry it yourself
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']
Fast membership testsTry it yourself
allowed = set("abcdef")
print(all(c in allowed for c in "cafe"), "z" in allowed)

Output

True False

Common mistakes

  • {} creates an empty dict; use set() 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

VersionChange
Python 3.0Added