Python Set

Beginner
9 min read
Updated: Nov 2026
3 examples
Unique items

Definition and Usage

A set stores unique items with no order, like a bag of different marbles: you can drop one in or take one out, but you cannot ask for "the third marble", and a second marble of the same kind is never kept.

A set is unordered, mutable, holds only unique values, and every item must be hashable. The Set Methods index lists every guide, such as add(), discard(), and union().

Python Syntax

Curly braces hold items separated by commas; in asks whether a value is in the set, and | joins two sets:

Python
fruits = {"apple", "banana", "cherry"}  # a set literal
fruits.add("apple")                     # duplicates are ignored
print(len(fruits))                      # 3
print("kiwi" in fruits)                 # False
print(sorted(fruits))                   # ['apple', 'banana', 'cherry']
fruits.discard("banana")                # remove one item
print(sorted(fruits | {"kiwi"}))        # ['apple', 'cherry', 'kiwi']
for fruit in sorted(fruits):
    print(fruit)
Order is never promised.

Printing a set or looping over it may show the items in any order, and for strings the order can change from one run to the next. When you need a stable result, use sorted(fruits), which returns a list in a fixed order. Every example on this page does that.

How Sets Behave

RuleWhat it means
Unique itemsEach value is stored once. Adding a value that is already there changes nothing, so {1, 1, 2} is the same set as {1, 2}.
UnorderedItems have no position: there is no s[0], and the order you see when printing or looping is not something you can rely on. Use sorted(s) for a fixed order.
MutableYou can add and remove items after the set is created. Two names bound to the same set see the same changes.
Hashable items onlyNumbers, strings, tuples of those, and frozenset can be items. A list, dict, or set cannot, and raises TypeError.
Fast membershipx in s is very quick even when the set is huge, which is why sets are good for "have I seen this?" checks.
Equal values collapse1, 1.0, and True are equal, so a set keeps only the first one you add.

Creating Sets

CodeWhen to use it
{2, 3, 5, 7}Literal: the most common way for a few known values.
set()The only way to make an empty set, because {} is an empty dict.
set([4, 4, 9])From any iterable; the repeated 4 is dropped. A quick way to remove duplicates.
set("hello")A string gives one item per different character.
{n % 3 for n in nums}Set comprehension: compute each item.
frozenset([1, 2])An unchangeable set; it can be a set item or a dict key.

The set() constructor turns any iterable into a set and drops the duplicates, and frozenset() does the same for an unchangeable set. An empty set is always set(), never {}.

Set Math: Operators and Methods

Sets answer "what do these two groups have in common?" in one line. Each question has an operator and a method:

QuestionOperatorMethod
Everything from botha | ba.union(b)
Only the shared itemsa & ba.intersection(b)
In a but not in ba - ba.difference(b)
In exactly one of thema ^ ba.symmetric_difference(b)
Is a inside b?a <= ba.issubset(b)
Does a contain b?a >= ba.issuperset(b)
Do they share nothing?no operatora.isdisjoint(b)

The operators need a set on both sides, while the methods also accept lists, tuples, and strings. Add _update to a method name, or put = after an operator, to change the set in place.

Common Mistakes

MistakeDo this instead
s = {} for an empty setThat makes an empty dict. Write s = set() instead.
print(s) and expecting an orderA set has no order, and string items can print differently from run to run. Use print(sorted(s)).
x = s.add(1)add() changes the set and returns None, so x is None. Call s.add(1) on its own line.
s.add([1, 2])A list is unhashable and raises TypeError. Add a tuple, (1, 2), instead.
s[0]A set has no positions, so this raises TypeError. Loop over the set, or use sorted(s)[0] for the smallest item.
remove() on a missing itemIt raises KeyError. Use discard() when the item may be absent.
set("hello") to store a wordA string is split into its characters. Use {"hello"} or s.add("hello") to store the whole word.

Set vs List vs Tuple vs Dict

TypeLiteralBest forContentsChange it?
set{1, 2}Unique items, fast membership tests, set mathUnique, hashable items; no orderMutable
list[1, 2, 1]Ordered items you will changeDuplicates allowedMutable
tuple(1, 2, 1)Fixed records, dict keysDuplicates allowedImmutable
dict{"a": 1}Look up values by keyUnique keys, insertion orderMutable

Read more about ordered items on the Python List page and about key/value lookups on the Python Dict page.

Python Examples

Fixed data only, and every set is printed with sorted(), so the output is the same on every machine.

Example 1 — Create Sets Five Different Ways

A literal, set() on a string and on a list with repeats, a set comprehension, and the empty set.

Python
primes = {2, 3, 5, 7}
letters = set("hello")
unique = set([4, 4, 9, 9, 9, 1])
mods = {n % 3 for n in range(10)}
empty = set()

print(sorted(primes), len(primes))
print(sorted(letters))
print(sorted(unique))
print(sorted(mods))
print(empty, len(empty), type({}).__name__)

How It Works

  1. Literal braces. Curly braces around comma-separated values make a set, and len() counts its items.
  2. Duplicates vanish. set("hello") keeps one "l", and the list with repeated 4s and 9s shrinks to three different numbers.
  3. A set comprehension. The numbers 0 to 9 leave remainders 0, 1, and 2 when divided by 3, and each remainder is stored once.
  4. The empty set. Only set() makes an empty set, because {} is an empty dict, which is why type({}) prints dict.

Example 2 — Compare Two Study Groups With Set Math

Use |, &, -, ^, in, and <= on two sets of students.

Python
math_club = {"Ana", "Ben", "Cho", "Dev"}
art_club = {"Cho", "Dev", "Eli"}

print(sorted(math_club | art_club))
print(sorted(math_club & art_club))
print(sorted(math_club - art_club))
print(sorted(math_club ^ art_club))
print("Ben" in math_club, "Ben" in art_club)
print({"Cho", "Dev"} <= math_club)

How It Works

  1. Union. | collects everyone from both clubs, and Cho and Dev are listed once even though they are in both.
  2. Intersection and difference. & keeps the two shared students, while - keeps those only in the math club.
  3. Symmetric difference. ^ keeps students in exactly one club: Ana and Ben from math, and Eli from art.
  4. Membership and subsets. in asks about one student, and <= asks whether the whole set {"Cho", "Dev"} fits inside the math club.

Example 3 — Hit Three Classic Set Mistakes on Purpose

Using {} for an empty set, adding a list, and storing the result of add().

Python
empty = {}
print(type(empty).__name__)
empty = set()
print(len(empty))

try:
    bad = {[1, 2], 3}
except TypeError:
    print("a list cannot be a set item")

result = empty.add(5)
print(result, empty)

How It Works

  1. {} is a dict. The first variable is an empty dictionary, and set() is the only way to get an empty set.
  2. Only hashable items. A list can change, so putting [1, 2] inside a set literal raises TypeError; use a tuple (1, 2) instead.
  3. add() returns None. add() changes the set and hands back nothing, so result is None and the set now holds 5.

Next: Python Set Methods by Group

Frequently Asked Questions

A set is a built-in, unordered, mutable collection of unique, hashable items written in curly braces, such as {1, 2, 3}. It is ideal for removing duplicates and testing membership.
Use set(). Writing {} creates an empty dict, not an empty set.
A set has no order, and the layout depends on the hash values of its items, which can change between runs for strings. Use sorted(s) when you need a stable order.
Both delete an item and return None. If the item is missing, remove() raises KeyError, while discard() does nothing.
Use a set when you need unique items, quick membership tests, or set math such as union and intersection. Use a list when order or duplicates matter.

Browse every set method

Open the method index for categorized guides with examples and FAQs.

Set Methods Index →

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.

13 people found this page helpful