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_setstays 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.
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)fruits refers to a set with three unique strings.numbers holds 1, 2, and 3.set().{} is an empty dictionary. This is why set() is needed for an empty set.len() counts the unique items. The output is 3 3.sorted() returns the items as a list in ascending order. The output is [1, 2, 3].<class 'set'> <class 'dict'>.set("hello") collects the characters h, e, l, l, o, and the repeated l is kept once. The result equals the set written on the right, so the output is True.[5, 3, 5, 1, 3] becomes the set {1, 3, 5}. The output is [1, 3, 5].in tests whether a value is in the set. The output is True False.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 aKeyErrorif 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 aKeyErroron 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.
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){"red", "green"}."blue". The set now has three items."red" is already in the set, so nothing changes and no error occurs.['blue', 'green', 'red'].update() adds every item of the list. The set now has five items.5.remove("green") deletes the item. The set has four items left."purple" is not in the set. Because discard() ignores missing items, no error occurs.['black', 'blue', 'pink', 'red'].pop() removes one item and returns it. Which item it picks is not defined, so never depend on it.3 False.clear() removes everything but keeps the set itself.set(), and not as {}.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 | bora.union(b): all items that are ina, inb, or in both. - Intersection
a & bora.intersection(b): only the items that are in both. - Difference
a - bora.difference(b): the items ofathat are not inb. The order matters. - Symmetric difference
a ^ bora.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.
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))a holds the numbers 1 to 4.b holds the numbers 3 to 6. The numbers 3 and 4 are in both sets.[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6].[3, 4] [3, 4].a - b keeps the items of a that are not in b, and b - a does the opposite. The output is [1, 2] [5, 6].[1, 2, 5, 6].4 4.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.
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)small holds 1 and 2.big holds 1, 2, 3, and 4. It contains every item of small.other holds 8 and 9. It shares nothing with the other two sets.small <= big asks whether small is a subset, small < big asks for a proper subset, and big >= small asks whether big is a superset. All three are true. The output is True True True.issubset() and issuperset() ask the same questions. The output is True True.small and other have no common item, so the first result is true. small and big share 1 and 2, so the second is false. The output is True False.{1, 2} equals {2, 1}. The output is True.True False.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.
{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))a is {1, 2, 3}.|= adds the items 4 and 5 to a.[1, 2, 3, 4, 5].&= keeps only the items that are also in the right-hand set, which are 2, 3, and 4. The value 9 is not in a, so it does not appear.[2, 3, 4].-= removes the items of the right-hand set, so the 2 is deleted.[3, 4].^= keeps the items that are in exactly one of the two sets. The 3 is in both, so it is removed, and the 10 is new, so it is added.[4, 10].b is {1, 2}.[1, 2, 3, 4].[2, 3, 4].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.
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]))words holds six words, but only three different ones.set(words) keeps one copy of each word.6 3.['apple', 'kiwi', 'pear'].dict.fromkeys(words) makes a dictionary whose keys are the words. The keys are unique and stay in the order of their first appearance. list() turns the keys into a list.['pear', 'apple', 'kiwi'].text refers to the string "mississippi".['i', 'm', 'p', 's'].4.True.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.
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}))[0, 1, 4, 9]."programming" that are vowels. The letters o, a, and i pass the test.['a', 'i', 'o'].sorted() of the set gives the items in alphabetical order, so the output is always the same.a, b, and c.n % 2 == 0 is true: 0, 2, 4, 6, and 8.[2, 4].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.
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)frozenset() turns the list into an immutable set.[1, 2, 3] 3.AttributeError.add() method, so Python raises an AttributeError.error.Error: 'frozenset' object has no attribute 'add'.{2, 1} equals the key {1, 2}, because order does not matter. The output is pair.(0, 0) is written twice and kept once.2.TypeError.TypeError.error.Error: unhashable type: 'list'.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.
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))lower() makes every letter lowercase, so Python and python would count as the same word. split() then gives the list of seven words.set(words) keeps one copy of each word. The words is and fun each appear twice, so five unique words remain.Total words: 7.Unique words: 5.Sorted: ['and', 'fun', 'is', 'java', 'python'].words.count(w) is greater than 1. The words is and fun qualify.Repeated: ['fun', 'is'].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.
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){"bob", "dave", "erin"}.bob and dave. The output is In both: ['bob', 'dave'].Only in A: ['alice', 'carol'].Only in B: ['erin'].All students: ['alice', 'bob', 'carol', 'dave', 'erin'].bob and dave. The output is In exactly one class: ['alice', 'carol', 'erin'].Same students? False.Common Mistakes with Sets
- Using
{}for an empty set: it creates an empty dictionary. Writeset(). - Indexing a set:
my_set[0]raises aTypeError, because sets have no positions. Convert to a list or usesorted()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. Usesorted()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 aKeyError. Usediscard(). - 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 + braises aTypeError. Usea | b. - Changing a set while looping over it: it raises a
RuntimeError. Loop over a copy, such asfor 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(), andclear()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, andlen(set(items))counts the distinct values.- Membership tests are very fast, and a
frozensetis 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.