Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python set() function

Reference for Python set(): create a set from an iterable, remove duplicates, the empty-set trap, hashable items, set operations and ordering caveats.

set is the built-in type for an unordered collection of unique, hashable items. Calling set(iterable) builds a set from any iterable, silently dropping duplicates. Membership tests (x in s) are very fast because sets are backed by a hash table.

Sets also support the usual mathematical operations: union, intersection, difference and symmetric difference. Sets are mutable; for an immutable, hashable version use frozenset().

Python
set([3, 1, 3, 2])   # {1, 2, 3}
set("hello")        # {'h', 'e', 'l', 'o'} (order may vary)
set()               # empty set, NOT {}

Try it

Python Creating sets and removing duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Set operations, mutation and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set()
set(iterable)
{item1, item2, ...}   # set literal (at least one item)
Name Description
iterable Optional. Any iterable whose items are hashable. A string gives its characters, a dict gives its keys.

Return value: a new set. The original iterable is not changed.

Raises: TypeError if the argument is not iterable or an item is unhashable (a list, dict or another set).

Usage notes

  • {} is an empty dict, not an empty set. Write set() for an empty set. {1, 2} with items is a set literal.
  • Items must be hashable. Numbers, strings, tuples of hashable items and frozensets are fine; lists, dicts and sets are not. Use tuples or frozensets to nest.
  • Order is not guaranteed and can differ between runs for strings (hash randomization). Never rely on it; print sorted(s) when you need a stable view. If you need to keep first-seen order while deduplicating, use list(dict.fromkeys(items)).
  • Duplicates by equality. 1, 1.0 and True count as the same item.
  • remove() raises KeyError if the item is missing; discard() does not. pop() removes and returns an arbitrary item, and fails on an empty set.
  • Operators need sets on both sides (a | b); the named methods (union, intersection...) accept any iterable.
  • Speed. Membership, add and discard are O(1) on average. Converting a list to a set to test many lookups is a standard speed-up.
  • Mutating while iterating a set raises RuntimeError; iterate over a copy.
  • Set comprehensions {x % 3 for x in range(10)} are the compact way to build one.