Glossary

Set

A set is an unordered collection of unique, hashable elements in Python. Sets are created with braces ({1, 2, 3}) or the set() constructor. (An empty set must be created with set(), since {} creates an empty dictionary.) Sets automatically discard duplicates: {1, 2, 2, 3} evaluates to {1, 2, 3}.

Sets support the classical mathematical operations: union (|), intersection (&), difference (-), and symmetric difference (^). They also support .add(x), .remove(x) (raises KeyError), .discard(x) (silent if absent), and .pop() (remove an arbitrary element). Membership testing (x in s) is O(1) on average, making sets ideal for deduplication, fast lookups, and computing relationships between collections.

The frozenset is the immutable counterpart of set. Because frozensets cannot be modified, they are hashable and can be used as dictionary keys or elements of another set. Set comprehensions ({x**2 for x in range(10)}) create sets concisely. Under the hood, CPython implements sets using hash tables similar to dictionaries but storing only keys, not key–value pairs.

Related terms: Mutable, Dictionary, Frozenset, Comprehension

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.