Home Python Built-in Functions set() Python set() Function 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.
unique = set(iterable)
colors = {"red", "green"}
empty = set() Call What 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 set(iterable=(), /)
# class set: a mutable built-in type Parameters Parameter Description iterable Optional. An iterable of hashable items. Default: empty.
Return Value Return Value Description set A new set containing the unique items.
Important
Do not rely on the order of a set: it depends on hash values, and string hashes are randomized per process. Unhashable items such as lists raise TypeError. remove() raises KeyError for a missing item; discard() does not. Use frozenset for an immutable, hashable set.
Python Examples 1. Remove duplicates 2. Set operations 3. Add and remove Example 1 — Remove Duplicates and Count Unique Items Collapse repeated numbers and letters into unique items.
numbers = [3, 1, 3, 2, 1, 3]
unique = set(numbers)
print(len(numbers), len(unique))
print(sorted(unique))
print(sorted(set("mississippi")))
print(set()) 6 3
[1, 2, 3]
['i', 'm', 'p', 's']
set() How It Works Duplicates vanish. Six numbers collapse to three unique values.Sort for display. sorted(unique) returns a list in a predictable order.Unique letters. "mississippi" uses only four different letters.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_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) ['ben', 'dev']
['ana', 'ben', 'chen', 'dev', 'eli']
['ana', 'chen']
['ana', 'chen', 'eli']
True False How It Works Intersection &. Only ben and dev are in both teams.Union |. All five people appear once each.Difference and symmetric difference. - keeps Python-only members; ^ keeps people in exactly one team.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.
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") 2 ['python', 'tips']
remove() raises KeyError for a missing item
lists are unhashable and cannot be set items How It Works add() ignores repeats. Adding "python" a second time leaves the size at 2.discard() is forgiving. Discarding a missing item silently does nothing.remove() is strict. The same call with remove() raises KeyError.Hashable items only. Lists can change, so they have no hash and cannot go into a set.Frequently Asked Questions How do I remove duplicates from a list in Python? Use list(set(items)) if order does not matter, or list(dict.fromkeys(items)) to keep the first-seen order.
How do I create an empty set? Call set(). The literal {} creates an empty dict, not a set.
Why does my set print in a different order? Sets are unordered. The order depends on hash values, and string hashes change between runs. Use sorted(my_set) for stable output.
What is the difference between remove() and discard()? Both delete an item. remove() raises KeyError if the item is missing; discard() does nothing.
Can a set contain a list? No, set items must be hashable. Use a tuple instead of a list, or a frozenset instead of a set.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion