Skip to contentSkip to navigation

Module 04 · Lesson 02

Set Creation & Deduplication

Keep only unique values with sets: remove duplicates, test membership quickly, combine groups with union, intersection and difference, and see how sets and dictionary keys relate.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Remove repeats
  • Check with in
  • Combine with & and |
  • Watch two clubs compare

Each value only once

A set is a bag of values where nothing appears twice. It is great for removing repeats and for quick "is it there?" checks.

  • Unique

    {1, 2, 2, 3} keeps 1, 2 and 3. Repeats simply disappear.

  • No positions

    A set has no first or last item, so there is no [0]. Use in to check for a value.

  • Add and remove

    add() puts a value in, discard() takes it out with no error if it is missing.

  • Combine

    a | b is everything, a & b is what both share, a - b is what only a has.

Sets at work

Any time the question is "who or what, without repeats?", think set.

  • UsernamesA sign-up page checks the set of taken names before you pick one.
  • BadgesCollecting the same badge twice still counts as one badge.
  • Friends in commonmine & yours shows the friends two people share.
  • TagsA post's tags are a set: adding #python twice still shows it once.

Repeats disappear

This line turns a list with repeats into a set. Tap each part to see its job.

Part 1 of 2

Tap any part of the code below, or press Next.1 of 2 explored

make a set:set() builds a set from anything with items in a row, dropping every repeat.

Prints {1, 2, 3}

Keep only one of each

Pick an example, change it, then press Run. Say what you expect to see before you press. Sets of words print in a changing order, so these use `sorted()` to show them.

Example 1 of 6Remove repeats

Turn a list into a set and the repeats are gone.

Your turn: Add more rolls until all six numbers have come up.

Python
rolls = [6, 2, 6, 3, 2, 6, 1]
unique = set(rolls)
print(unique)
print(len(rolls), "rolls,", len(unique), "different numbers")
Output
Press Run to see what it prints.

Watch two clubs compare lists

Press Step to run one line at a time. The numbers are pupil ticket numbers from two clubs.

Ready. Press Step to run the first line.

  1. chess = {1, 2, 3, 4}
  2. art = {3, 4, 5}
  3. both = chess & art
  4. either = chess | art
  5. only_chess = chess - art
  6. print(both)
  7. print(len(either), only_chess)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.How many are left?

print(len({1, 1, 2, 2, 2}))

0 of 6 answered

Common set misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Collections of unique values

A set is an unordered collection with no duplicates. You write one with curly braces, like a dictionary but with single values instead of pairs.

Try it 1: edit me, then Run
colours = {"red", "green", "red", "blue"}
print(len(colours))        # 3, the second red is dropped
print("red" in colours)    # True
Output
Press Run to see what it prints.

Adding a value that is already in a set changes nothing. That single rule makes sets the standard tool for removing duplicates: set(items) keeps one of each.

Try it 2: edit me, then Run
visits = [101, 102, 101, 103, 102, 101]
unique = set(visits)
print(len(unique))         # 3 different visitors
print(sorted(unique))      # [101, 102, 103]
Output
Press Run to see what it prints.

Unordered means no positions

A set has no order and no indexes, so colours[0] is a TypeError. When a set of strings is printed, the order can even change from one run of the program to the next. Whenever order matters, for display or for a test, turn the set into a sorted list with sorted(). A set is for asking "is this in the group?" and "how big is the group?", not "what comes first?".

The empty set

{} already means an empty dictionary, so the empty set is written set(). This catches out everyone once.

Try it 3: edit me, then Run
print(type({}))            # <class 'dict'>
print(type(set()))         # <class 'set'>
Output
Press Run to see what it prints.

Adding and removing

Try it 4: edit me, then Run
tags = {"python"}
tags.add("beginner")
tags.add("python")         # already there: no change
tags.discard("advanced")   # not there: no error
tags.remove("beginner")    # there: removed
print(tags)                # {'python'}
Output
Press Run to see what it prints.

remove(x) raises KeyError if x is missing, while discard(x) quietly does nothing. Use remove() when a missing item would mean a bug, and discard() when it is normal. pop() removes and returns an arbitrary item, and clear() empties the set.

Only hashable values can go in a set, the same rule as dictionary keys: numbers, strings and tuples work, but lists and other sets do not.

Fast membership

To check x in some_list, Python looks at the items one by one, so a list of a million items can take a million comparisons. A set uses the same hashing as a dictionary and jumps straight to where x would be, so the check takes about the same time however large the set is. If a program repeatedly asks whether values are in a large group, convert the group to a set once and test against that.

Combining sets

Sets support the operations you may know from Venn diagrams. Each has an operator and a method with the same result.

Try it 5: edit me, then Run
art = {"Ana", "Bo", "Cy"}
music = {"Bo", "Cy", "Dee"}
print(sorted(art | music))   # union: in either       ['Ana', 'Bo', 'Cy', 'Dee']
print(sorted(art & music))   # intersection: in both   ['Bo', 'Cy']
print(sorted(art - music))   # difference: art only    ['Ana']
print(sorted(art ^ music))   # in exactly one          ['Ana', 'Dee']
Output
Press Run to see what it prints.

The methods are union(), intersection(), difference() and symmetric_difference(). They accept any iterable, so art.union(["Eve"]) works with a list, while the operators need sets on both sides. None of these change the original sets; they all return new ones. Note that difference is one-sided: art - music and music - art are different.

Comparisons check how two sets relate. a <= b is True when every item of a is also in b, meaning a is a subset of b; a >= b checks the other way. a.isdisjoint(b) is True when they share nothing. == is True when both hold exactly the same items, whatever order they were written in.

Sets and dictionaries

Sets and dictionaries are close relatives. Both store their items by hash, both require hashable values, and both give fast in checks. You can think of a set as a dictionary that has keys but no values. That connection is useful: the keys of a dictionary behave like a set, so you can combine them directly.

Try it 6: edit me, then Run
stock = {"tea": 5, "cake": 0, "jam": 2}
order = {"tea", "scone", "jam"}
print(sorted(order - stock.keys()))   # ['scone'], not sold here
print(sorted(order & stock.keys()))   # ['jam', 'tea']
Output
Press Run to see what it prints.

Choose a set when you only care whether something is present. Choose a dictionary when each item needs extra information attached, such as a count, a price or a name. Counting needs a dictionary; "have we seen this before?" needs a set.

Sets also change in place with augmented operators: seen |= new_items adds every new item to seen, and todo -= done removes everything already finished. These update the set on the left instead of building a new one, which is handy inside a loop that keeps adding to the same group.

Frozen sets

A normal set is mutable. frozenset(items) makes an immutable version that cannot be changed and is therefore hashable, so it can be a dictionary key or an item in another set. You will rarely need it in this course, but you may meet it in other people's code.

Typical uses

In everyday programs, sets usually appear in three places: removing duplicates before counting or displaying, remembering what has already been seen inside a loop, and comparing two groups to find what they share or what is missing. Each of these is a one-line job with a set and a fiddly loop without one.

Syntax

The general shape of the statements in this lesson.

syntax.py
s = {1, 2, 3}     s = set()      s = set(items)   # set() is empty
s.add(x)   s.remove(x)   s.discard(x)   x in s
a | b   a & b   a - b   a ^ b                    # union, both, only a, exactly one
a <= b   a >= b   a.isdisjoint(b)   a == b
sorted(s)                                        # order for display
order - stock.keys()                             # dictionary keys act like a set
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Unique words in a message

Beginner

Count how many different words a message uses, ignoring case, and list them in alphabetical order.

Python
message = "the cat saw the other cat and the dog"
words = message.lower().split()
unique = set(words)
print("Words:", len(words))
print("Different words:", len(unique))
print(sorted(unique))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Splitting gives a list with every word, duplicates included. Turning it into a set keeps one of each, so its length is the number of different words. sorted() turns the set into an ordered list for printing, which also makes the output the same every time.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Using {} for an empty set

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
seen = {}
seen.add(5)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

AttributeError: 'dict' object has no attribute 'add'

Write this instead

seen = set()
seen.add(5)

Why it happens

{} is an empty dictionary, and dictionaries have no add method.

In the real world

Where this shows up in software people use every day.

  1. Checking a guest list at the door

    Events

    A birthday party has an invitation list. As guests arrive, the host checks each name and records arrivals, making sure nobody is counted twice.

    Why Python fits

    One set holds the fixed invitations and another grows as people arrive. Membership tests decide each case, and a difference reports who is still to come.

    Python
    invited = {"Ana", "Bo", "Cy", "Dee"}
    arrived = set()
    for name in ["Bo", "Ana", "Zed", "Bo"]:
        if name not in invited:
            print(f"{name}: not on the list")
        elif name in arrived:
            print(f"{name}: already here")
        else:
            arrived.add(name)
            print(f"{name}: welcome")
    print("Still to come:", sorted(invited - arrived))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why does my set print in a strange order?

Sets do not keep order, and for strings the order can change between runs. Use sorted(s) whenever the order matters.

How do I remove duplicates but keep the original order?

Loop over the list, keep a set of values already seen, and append each value to a new list only the first time you meet it.

Can a set hold lists?

No, lists are not hashable. Use tuples instead, for example a set of (x, y) points.

Is a set always faster than a list?

For checking whether an item is present, yes, once there are more than a handful of items. For keeping order, counting repeats or reading by position, a list or a dictionary is the right tool.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 6 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.