Academic Block

Python Sets & Set OperationsGet Certified

What Is a Set?

A set is an unordered collection of unique items. If you add the same value twice, the set keeps only one copy. Sets are modeled on the sets of mathematics, so they come with the familiar operations of union, intersection, and difference. In Python the type is called set, and a set is written with curly braces: {1, 2, 3}. Sets are the right tool when you care about which values are present, and not about their order or how often they occur: removing duplicates, checking membership quickly, and comparing two groups of items.

  • Unique: a value can appear only once in a set.
  • Unordered: a set has no positions, so there is no indexing or slicing, and the display order is not something to rely on.
  • Mutable: you can add and remove items. Its immutable twin is the frozenset.
  • Hashable items only: the items must be immutable, such as numbers, strings, and tuples. A list cannot be a member of a set.
  • Fast membership tests: x in my_set stays fast even for very large sets.
  • Set algebra: |, &, -, and ^ combine and compare sets.
Note: Because a set has no fixed order, the examples on this page print sets with sorted(). That gives you a list in a predictable order, so that the output you see always matches the explanation.

Creating Sets

Write the items inside curly braces, or convert any iterable with the set() function. Duplicates are dropped automatically. There is one classic trap: {} with nothing inside is an empty dictionary, not an empty set. To create an empty set, write set(). Converting a string with set() gives its individual characters, so set("hello") has four items, because the letter l appears only once. The len() function counts the items, and the in operator tests membership.

Try It: Creating Sets

Click Test My Code. Notice that numbers was written with five values but holds only three.

What this code does: It creates a set of strings, a set from numbers with duplicates, an empty set, and an empty dictionary. It prints the sizes, a sorted list of the numbers, and the types of the two empty containers. It then converts a string and a list to sets and tests membership.
fruits = {"apple", "banana", "cherry"}
numbers = {3, 1, 2, 3, 1}
empty_set = set()
empty_dict = {}
print(len(fruits), len(numbers))
print(sorted(numbers))
print(type(empty_set), type(empty_dict))
print(set("hello") == {"h", "e", "l", "o"})
print(sorted(set([5, 3, 5, 1, 3])))
print("apple" in fruits, "grape" in fruits)

Adding and Removing Items

Sets are mutable, so you can change them after they are created. There is no index to assign to, so items are added and removed by value.

  • add(x) adds one item. If it is already there, nothing happens.
  • update(iterable) adds all the items of one or more iterables.
  • remove(x) deletes an item and raises a KeyError if it is missing.
  • discard(x) deletes an item and does nothing if it is missing. This is the safer choice.
  • pop() removes and returns an arbitrary item. It raises a KeyError on an empty set.
  • clear() removes every item.

Try It: Changing a Set

Click Test My Code. Then change discard("purple") to remove("purple") and read the error.

What this code does: It adds items one at a time and in bulk, and shows that adding an existing item changes nothing. It removes items with remove() and discard(), pops an arbitrary item, and finally empties the set.
colors = {"red", "green"}
colors.add("blue")
colors.add("red")
print(sorted(colors))
colors.update(["pink", "black"])
print(len(colors))
colors.remove("green")
colors.discard("purple")
print(sorted(colors))
item = colors.pop()
print(len(colors), item in colors)
colors.clear()
print(colors)

Union, Intersection, Difference, and Symmetric Difference

Set operations combine two sets into a new one and leave the originals unchanged. Each operation has an operator and an equivalent method. The methods also accept any iterable, such as a list, while the operators require two sets.

  • Union a | b or a.union(b): all items that are in a, in b, or in both.
  • Intersection a & b or a.intersection(b): only the items that are in both.
  • Difference a - b or a.difference(b): the items of a that are not in b. The order matters.
  • Symmetric difference a ^ b or a.symmetric_difference(b): the items that are in exactly one of the two sets.

Try It: The Four Set Operations

Click Test My Code. Draw two overlapping circles on paper, put the numbers in them, and check each result.

What this code does: It creates two sets that share the numbers 3 and 4. It calculates the union, the intersection, both differences, and the symmetric difference, each time with an operator and a method where both exist. It finally shows that the original sets still have four items each.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(sorted(a | b), sorted(a.union(b)))
print(sorted(a & b), sorted(a.intersection(b)))
print(sorted(a - b), sorted(b - a))
print(sorted(a ^ b))
print(len(a), len(b))

Subsets, Supersets, and Disjoint Sets

Comparison operators tell you how two sets relate to each other. A set A is a subset of B if every item of A is also in B. Then B is a superset of A. Two sets are disjoint when they have nothing in common. The operators <= and >= allow equal sets, while < and > mean a proper subset or superset: the sets must not be equal. Two sets are equal with == when they hold the same items, in any order.

Try It: Comparing Sets

Click Test My Code. Add 3 to the set other and see how the disjoint tests change.

What this code does: It builds a small set, a bigger set that contains it, and a third set with different numbers. It tests subset, proper subset, and superset relations with operators and methods, tests for disjoint sets, checks that the order of items does not matter for equality, and compares a set with itself.
small = {1, 2}
big = {1, 2, 3, 4}
other = {8, 9}
print(small <= big, small < big, big >= small)
print(small.issubset(big), big.issuperset(small))
print(small.isdisjoint(other), small.isdisjoint(big))
print({1, 2} == {2, 1})
print(big <= big, big < big)

In-Place Operations and update Methods

Each set operation also has an in-place form that changes the left-hand set instead of creating a new one. The operator forms are |=, &=, -=, and ^=. The matching methods are update(), intersection_update(), difference_update(), and symmetric_difference_update(). The method forms accept several iterables at once, including lists and tuples.

Try It: Changing a Set in Place

Click Test My Code. Follow the set on paper after each line, and compare it with the printed list.

What this code does: It starts with the set {1, 2, 3} and applies the four in-place operators one after another, printing the set after each step. It then shows that update() accepts a set and a list together, and removes an item with difference_update().
a = {1, 2, 3}
a |= {4, 5}
print(sorted(a))
a &= {2, 3, 4, 9}
print(sorted(a))
a -= {2}
print(sorted(a))
a ^= {3, 10}
print(sorted(a))
b = {1, 2}
b.update({2, 3}, [4])
print(sorted(b))
b.difference_update({1})
print(sorted(b))

Removing Duplicates and Counting Unique Items

The most common use of a set is to remove duplicates: set(items) keeps one copy of each value, and len(set(items)) counts the distinct values. The price is that the original order is lost. If you need to keep the order of first appearance, use list(dict.fromkeys(items)). A dictionary remembers the order in which keys were added, and its keys are unique, so this trick removes duplicates and keeps the order. You will learn more about dictionaries in the next lesson.

Try It: Unique Values

Click Test My Code. Compare the sorted list of unique words with the list that kept the original order.

What this code does: It counts the unique words of a list, shows them in sorted order, and removes duplicates while keeping the first-appearance order. It then finds the distinct letters of a word and checks whether a list contains only unique values by comparing its length with the length of its set.
words = ["pear", "apple", "pear", "kiwi", "apple", "pear"]
unique = set(words)
print(len(words), len(unique))
print(sorted(unique))
ordered = list(dict.fromkeys(words))
print(ordered)
text = "mississippi"
print(sorted(set(text)))
print(len(set(text)))
print(len(set([1, 2, 3])) == len([1, 2, 3]))

Set Comprehensions and Looping

Like lists, sets have a comprehension form, written with curly braces: {expression for item in iterable if condition}. The result is a set, so duplicates disappear automatically. You can loop over a set with a for loop, but the items arrive in no particular order. When the order matters, loop over sorted(my_set). Do not add or remove items of a set while you loop over it, because that raises a RuntimeError.

Try It: Set Comprehensions

Click Test My Code. Change range(-3, 4) to range(-5, 6) and predict how many squares you get.

What this code does: It builds a set of squares from positive and negative numbers, so that equal squares appear only once. It collects the vowels of a word with a filter, loops over a set in sorted order, and intersects a comprehension result with another set.
squares = {n * n for n in range(-3, 4)}
print(sorted(squares))
vowels = {ch for ch in "programming" if ch in "aeiou"}
print(sorted(vowels))
for letter in sorted({"b", "a", "c"}):
    print(letter)
evens = {n for n in range(10) if n % 2 == 0}
print(sorted(evens & {2, 4, 20}))

frozenset and What Can Go Inside a Set

The items of a set must be hashable, which means that they have a value that never changes. Numbers, strings, and tuples of such items are fine. Lists, dictionaries, and other sets are not, because they can change. A frozenset is an immutable set. It has all the reading methods and operators of a set, but none that change it, and because it cannot change, it is hashable. This makes a frozenset usable as a member of another set or as a dictionary key.

Try It: frozenset and Hashability

Click Test My Code. The try and except lines catch the errors so that the program can go on. They are explained in the lesson on errors and exceptions.

What this code does: It creates a frozenset and shows that it cannot be changed. It uses frozensets as dictionary keys, shows that a set of tuples works and drops duplicates, and shows the error that occurs when you try to put lists in a set.
fs = frozenset([1, 2, 3])
print(sorted(fs), len(fs))
try:
    fs.add(4)
except AttributeError as error:
    print("Error:", error)
groups = {frozenset({1, 2}): "pair", frozenset({3}): "single"}
print(groups[frozenset({2, 1})])
points = {(0, 0), (1, 2), (0, 0)}
print(len(points))
try:
    bad = {[1, 2], [3]}
except TypeError as error:
    print("Error:", error)
Tip: Testing membership in a list means looking at the items one by one, which gets slower as the list grows. A set finds an item almost instantly, whatever its size. If your program repeatedly asks “is this value in that collection?”, convert the collection to a set once, and test against the set.

Using Sets with User Input

Sets are a good fit for questions about groups: who is in both lists, which words occur, which values are missing. Read a line, split it into words, and convert the list to a set. The input is always text, so apply lower() first when upper and lower case should count as the same word.

Try It: Unique and Repeated Words

The Program Input box is already filled with Python is fun and Java is fun. Click Run Code straight away, then try your own sentence.

What this code does: It reads a sentence, converts it to lowercase, and splits it into words. It counts all the words and the unique words with a set, prints the unique words in alphabetical order, and uses a set comprehension and count() to find the words that occur more than once.
words = input("Enter words separated by spaces: ").lower().split()
unique = set(words)
print("Total words:", len(words))
print("Unique words:", len(unique))
print("Sorted:", sorted(unique))
duplicates = {w for w in unique if words.count(w) > 1}
print("Repeated:", sorted(duplicates))

Try It: Comparing Two Classes

The Program Input box is filled with two lines: alice bob carol dave and bob dave erin. Click Run Code, then type your own names.

What this code does: It reads the names of two classes into two sets, one line for each. It then uses the set operations to find the students who are in both classes, only in the first class, only in the second class, in either class, and in exactly one class. The last line checks whether the two classes are the same.
class_a = set(input("Class A students: ").split())
class_b = set(input("Class B students: ").split())
print("In both:", sorted(class_a & class_b))
print("Only in A:", sorted(class_a - class_b))
print("Only in B:", sorted(class_b - class_a))
print("All students:", sorted(class_a | class_b))
print("In exactly one class:", sorted(class_a ^ class_b))
print("Same students?", class_a == class_b)

Common Mistakes with Sets

  • Using {} for an empty set: it creates an empty dictionary. Write set().
  • Indexing a set: my_set[0] raises a TypeError, because sets have no positions. Convert to a list or use sorted() if you need positions.
  • Relying on the order of a set: the display order can differ between runs, and the order of pop() is arbitrary. Use sorted() when the order matters.
  • Putting a list or a dictionary in a set: they are not hashable and raise a TypeError. Convert a list to a tuple first.
  • Using remove() for an item that may be missing: it raises a KeyError. Use discard().
  • Mixing up set("abc") and {"abc"}: the first gives the three characters, and the second gives a set with one string.
  • Using + to join sets: a + b raises a TypeError. Use a | b.
  • Changing a set while looping over it: it raises a RuntimeError. Loop over a copy, such as for x in set(my_set):.

Key Takeaways

  • A set is an unordered, mutable collection of unique, hashable items, written with curly braces. Use set() for an empty one.
  • Sets have no indexes. Use sorted() when you need a predictable order.
  • add(), update(), remove(), discard(), pop(), and clear() change a set. discard() never raises an error for a missing item.
  • | is union, & is intersection, - is difference, and ^ is symmetric difference. Each has a method and an in-place form.
  • <=, >=, isdisjoint(), and == describe how two sets relate to each other.
  • set(items) removes duplicates, and len(set(items)) counts the distinct values.
  • Membership tests are very fast, and a frozenset is an immutable set that can be used as a dictionary key.

Frequently Asked Questions

What is a set in Python?

A set is an unordered, mutable collection of unique items written with curly braces, such as {1, 2, 3}. It automatically removes duplicates, it has no indexes, and its items must be hashable. Sets support fast membership tests and mathematical operations such as union and intersection.

How do I create an empty set in Python?

Use set() with no arguments. Empty curly braces {} create an empty dictionary, not an empty set.

What is the difference between a set and a list in Python?

A list is ordered, allows duplicates, and supports indexing and slicing. A set is unordered, keeps only unique items, has no indexes, and tests membership much faster. Use a list when order and repeats matter, and a set when you care only about which values are present.

How do I remove duplicates from a list in Python?

Convert the list to a set with set(my_list), and back to a list with list() if you need one. This loses the original order. To keep the order of first appearance, use list(dict.fromkeys(my_list)).

How do I find the union, intersection, and difference of two sets in Python?

Use a | b or a.union(b) for the union, a & b or a.intersection(b) for the intersection, and a – b or a.difference(b) for the difference. Use a ^ b for the items that are in exactly one of the two sets. These operations return new sets and leave the originals unchanged.

What is the difference between remove() and discard() in a Python set?

Both delete an item from the set. If the item is missing, remove() raises a KeyError, while discard() silently does nothing. Use discard() when the item may not be present.

Are Python sets ordered?

No. Sets do not keep a defined order, so you cannot rely on the order in which items are displayed or looped over, and you cannot index them. Use sorted(my_set) to get the items as a list in a predictable order.

Can a set contain a list in Python?

No. The items of a set must be hashable, and a list is mutable, so adding one raises a TypeError. You can store tuples of immutable items, or use a frozenset, which is an immutable set that can be a member of another set.

Ready for the next step?Learn how to store data as key and value pairs.
Next: Dictionaries →