Velamuvi AIAcademy

Lesson 19 of 30 · Collections

Sets

Learn Python sets: collections with no duplicates. Remove repeated values, test membership quickly and compare groups with union, intersection and difference.

  • 7 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • What a set is and how it differs from a list
  • How to remove duplicates with a set
  • How to compare two groups with union, intersection and difference

A collection with no duplicates

A set is a collection where every item appears only once. If you add something that is already there, nothing happens.

Sets are written with curly brackets.

Try it yourselfPython
numbers = {3, 1, 2, 3, 3, 1}

print(numbers)
print(len(numbers))

Six values went in, but only three different ones exist, so the set has three items.

Sets have no order

A list remembers the order you put things in. A set does not. It has no positions, so you cannot use an index.

Try it yourselfPython
colours = {"red", "green", "blue"}
print(colours[0])

This raises TypeError: 'set' object is not subscriptable. It also means that when you print a set of words, they may appear in a different order each time. That is normal.

Removing duplicates from a list

This is the most common use of a set. Convert the list to a set, and the repeats vanish.

Try it yourselfPython
visitors = ["ada", "grace", "ada", "alan", "grace", "ada"]

unique_visitors = set(visitors)

print("Visits:", len(visitors))
print("Different people:", len(unique_visitors))

If you need a list again, and in a predictable order, sort it.

Try it yourselfPython
numbers = [4, 2, 4, 1, 2, 3, 1]

unique_sorted = sorted(set(numbers))
print(unique_sorted)

Adding and removing

Try it yourselfPython
skills = {"python", "sql"}

skills.add("git")
skills.add("python")     # already there: no change
skills.discard("sql")

print(len(skills))
print("git" in skills)

discard() removes an item and does nothing if it is missing. remove() also exists, but raises an error when the item is not there.

Comparing two groups

Sets can answer questions such as "what do these groups share?" in a single step.

Try it yourselfPython
python_class = {1, 2, 3, 4, 5}
sql_class = {4, 5, 6, 7}

print("In either class:", python_class | sql_class)
print("In both classes:", python_class & sql_class)
print("Only in Python: ", python_class - sql_class)
OperatorNameMeaning
a | bUnionEverything in a or b
a & bIntersectionOnly what is in both
a - bDifferenceWhat is in a but not in b

Fast membership checks

Asking x in my_set is extremely fast, even with millions of items. A list has to be searched from the start; a set can jump straight to the answer.

Try it yourselfPython
banned_words = {"spam", "scam", "fake"}
message = "this is not a scam"

for word in message.split():
    if word in banned_words:
        print("Blocked word found:", word)

Choosing a collection

  • List: ordered, can change, duplicates allowed. The default choice.
  • Tuple: ordered, cannot change. For fixed groups of values.
  • Set: no order, no duplicates. For uniqueness and fast "is it in here?" checks.

Common mistakes

Practice exercise

Remove the repeated numbers and print the unique values in order.

Your solutionPython
numbers = [4, 2, 4, 1, 2, 3, 1]

# Remove the duplicates and print the unique numbers
# as a sorted list. Output must be exactly: [1, 2, 3, 4]
Knowledge check

How many items are in the set {5, 5, 7, 7, 7, 9}?

Summary

  • A set holds unique items and has no order.
  • set(my_list) removes duplicates.
  • add() and discard() change a set.
  • |, & and - give the union, intersection and difference.
  • Checking in on a set is very fast.

Next: the collection that looks things up by name.

Finished reading? Tick it off to track your progress.