Python set() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in type

Definition

In Python, set(iterable) creates a set: a collection of unique items with no duplicates and no index positions. set([3, 1, 3]) contains just 1 and 3. Membership tests with in are very fast, even for large sets.

Sets support math-style operations: union |, intersection &, difference -, and symmetric difference ^. Items must be hashable (numbers, strings, tuples). An empty set is written set(), because {} is an empty dict.

set is a built-in type (a class) that you call like a function: each call creates a new set object. Like every built-in, it lives in the builtins module and is always available without an import.

Syntax

Pass an iterable, or write a literal with braces.

python
unique = set(iterable)
colors = {"red", "green"}
empty = set()
CallWhat it does
set([1, 1, 2])Returns {1, 2}.
set("hello")The unique letters h, e, l, o (in no particular order).
a | bUnion: items in either set.
a & bIntersection: items in both sets.

Set iteration order is not guaranteed and, for strings, changes between runs; the examples print sorted(...) to get a stable order.

Library declarations
python
set(iterable=(), /)
# class set: a mutable built-in type

Parameters

ParameterDescription
iterableOptional. An iterable of hashable items. Default: empty.

Return Value

Return ValueDescription
setA new set containing the unique items.

Python Examples

Example 1 — Remove Duplicates and Count Unique Items

Collapse repeated numbers and letters into unique items.

python
numbers = [3, 1, 3, 2, 1, 3]
unique = set(numbers)

print(len(numbers), len(unique))
print(sorted(unique))
print(sorted(set("mississippi")))
print(set())

How It Works

  1. Duplicates vanish. Six numbers collapse to three unique values.
  2. Sort for display. sorted(unique) returns a list in a predictable order.
  3. Unique letters. "mississippi" uses only four different letters.
  4. Empty set repr. An empty set prints as set(), because {} means an empty dict.

Example 2 — Union, Intersection, and Difference

Compare two teams with the four set operators and test membership.

python
python_devs = set(["ana", "ben", "chen", "dev"])
java_devs = set(["ben", "dev", "eli"])

print(sorted(python_devs & java_devs))
print(sorted(python_devs | java_devs))
print(sorted(python_devs - java_devs))
print(sorted(python_devs ^ java_devs))
print("eli" in java_devs, "eli" in python_devs)

How It Works

  1. Intersection &. Only ben and dev are in both teams.
  2. Union |. All five people appear once each.
  3. Difference and symmetric difference. - keeps Python-only members; ^ keeps people in exactly one team.
  4. Fast membership. in checks a set by hash, without scanning every item.

Example 3 — Add, Discard, Remove, and Unhashable Items

Grow a set, remove items safely, and see which values a set cannot hold.

python
tags = set()
tags.add("python")
tags.add("tips")
tags.add("python")
print(len(tags), sorted(tags))

tags.discard("missing")
try:
    tags.remove("missing")
except KeyError:
    print("remove() raises KeyError for a missing item")

try:
    set([[1, 2], [3]])
except TypeError:
    print("lists are unhashable and cannot be set items")

How It Works

  1. add() ignores repeats. Adding "python" a second time leaves the size at 2.
  2. discard() is forgiving. Discarding a missing item silently does nothing.
  3. remove() is strict. The same call with remove() raises KeyError.
  4. Hashable items only. Lists can change, so they have no hash and cannot go into a set.

Frequently Asked Questions

Use list(set(items)) if order does not matter, or list(dict.fromkeys(items)) to keep the first-seen order.
Call set(). The literal {} creates an empty dict, not a set.
Sets are unordered. The order depends on hash values, and string hashes change between runs. Use sorted(my_set) for stable output.
Both delete an item. remove() raises KeyError if the item is missing; discard() does nothing.
No, set items must be hashable. Use a tuple instead of a list, or a frozenset instead of a set.

Next: setattr()

Set an attribute by name.

setattr() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful