Sets

Published by Brayan K

A set is Python's collection of unique items. Drop duplicates in and they silently disappear; ask "is this here?" and you get an answer almost instantly. Sets are the right tool whenever uniqueness or fast membership matters.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A set keeps one of each value

A set is written as single values in curly braces, or made from a list or any other collection with set(). Duplicates are dropped as it's built:

nums = {3, 1, 3, 2, 1}
print(sorted(nums))
print(len(nums))

votes = ["yes", "no", "yes", "yes", "no"]
choices = set(votes)
print(len(choices), sorted(choices))
print("yes" in choices, "maybe" in choices)



# ✅ Expected output:
# [1, 2, 3]
# 3
# 2 ['no', 'yes']
# True False

Five votes, two different answers. A set has no guaranteed iteration order. The numbers above are displayed with sorted() so the output is stable. A set of strings can print in a different order across program runs, because the hash Python works out for a piece of text changes from one run to the next. When the order matters, sort the set: sorted(), from Lists and Collections, returns a sorted list.

Curly braces are also how a dictionary is written, and dictionaries had them first, so {} on its own is an empty dictionary, not an empty set:

seen = {}
seen.add("ada")

# ✅ Expected error:
# AttributeError: 'dict' object has no attribute 'add'

An empty set is written set(), and that's also how one prints:

seen = set()
print(seen, type(seen), type({}))
seen.add("ada")
print(len(seen))

# ✅ Expected output:
# set() <class 'set'> <class 'dict'>
# 1

No positions, and what can go in

Without an order there's no first item, so a set can't be indexed:

colors = {"red", "green", "blue"}
print(colors[0])

# ✅ Expected error:
# TypeError: 'set' object is not subscriptable

A for loop goes through a set in whatever order it gives, or loop over sorted(colors) for a fixed one. If you need positions, you need a list. Sets find their values by hash, as a dictionary finds its keys, so the same rule applies to what goes in: it has to be hashable, as Dictionaries explains. A list isn't: pairs.add([1, 2]) stops with TypeError: unhashable type: 'list', which Python 3.14 words cannot use 'list' as a set element (unhashable type: 'list'). A tuple works where a list doesn't:

pairs = set()
pairs.add((1, 2))
pairs.add((1, 2))
print(pairs)

# ✅ Expected output:
# {(1, 2)}

The second add() changed nothing: that pair was already there. Tuples covers tuples in full. A set can't hold another set either, since a set can change: {{1, 2}, {3}} stops with TypeError: unhashable type: 'set' (from 3.14, cannot use 'set' as a set element (unhashable type: 'set')). For the rare set of sets, frozenset() makes a set that can't change. Values that are equal count as one, so {1, True, 1.0} holds a single item: 1 == True == 1.0.

Adding and removing

add() puts in one value, update() every value of another collection, and discard() and remove() take one out:

tags = {"python", "code"}
tags.add("tutorial")
tags.add("python")
tags.update(["web", "css"])
print(len(tags))

tags.discard("java")
tags.remove("css")
print(sorted(tags))

# ✅ Expected output:
# 5
# ['code', 'python', 'tutorial', 'web']

Adding "python" a second time changed nothing. discard() removes a value if it's there and does nothing if it isn't, so "java" caused no error. remove() insists:

tags = {"python", "code"}
tags.remove("css")

# ✅ Expected error:
# KeyError: 'css'

A set's remove() raises a KeyError naming the value, where a list's gives ValueError: list.remove(x): x not in list. There's no append(): tags.append("x") stops with AttributeError: 'set' object has no attribute 'append'. pop() removes and returns a value, with no saying which, and on an empty set stops with KeyError: 'pop from an empty set'. As with a dictionary, adding to or removing from a set while a for loop goes through it stops the program, with RuntimeError: Set changed size during iteration.

Comparing two groups

Four operators answer the usual questions about two groups. Here they compare two readers' books, sorted so the output is the same every run:

ada = {"Dune", "1984", "Hobbit", "Sapiens"}
ben = {"1984", "Sapiens", "Foundation"}

print(sorted(ada & ben))
print(sorted(ada - ben))
print(sorted(ben - ada))
print(sorted(ada ^ ben))
print(len(ada | ben))

# ✅ Expected output:
# ['1984', 'Sapiens']
# ['Dune', 'Hobbit']
# ['Foundation']
# ['Dune', 'Foundation', 'Hobbit']
# 5

& keeps the books both have read, | combines everything, ^ keeps the books only one of them has read, and - keeps the books in the first set that aren't in the second, so ada - ben and ben - ada differ. {"1984"} <= ada asks whether every value of the left set is in the right one.

The operators need a set on both sides: ada | ["Emma"] stops with TypeError: unsupported operand type(s) for |: 'set' and 'list'. The methods with the same jobs, union(), intersection() and difference(), accept any collection: ada.union(["Emma"]) works. + isn't defined for sets at all: {1, 2} + {3} stops with TypeError: unsupported operand type(s) for +: 'set' and 'set'.

Fast "have I seen this?", and keeping the order

in on a list checks the items one by one until it finds a match. On a set it goes straight to where the value would be, through its hash, so the answer comes as fast for a million values as for ten. That makes a set the usual way to remember what's been seen. Turning a list into a set drops its duplicates, but also its order; this loop keeps both:

emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
print(len(set(emails)))

seen = set()
first_seen = []
for e in emails:
    if e not in seen:
        seen.add(e)
        first_seen.append(e)
print(first_seen)

# ✅ Expected output:
# 3
# ['[email protected]', '[email protected]', '[email protected]']

list(set(emails)) gives the three addresses in no particular order. The loop keeps them in the order they first appeared and uses the set only to ask "seen it?". Lists and Collections has a one-line way, list(dict.fromkeys(emails)), and Benchmarking with timeit measures how much faster in is on a set than on a list. Comprehensions build a set from a loop in one line, and Counter & defaultdict counts how many times each value appears, which a set forgets.

Practice: mutual friends

Fill the three blanks with the operators in the hint lines, in order: find the friends Maya and Omar share, the people Omar knows and Maya doesn't, and how many people they know between them.

maya = {"sam", "leo", "nina", "kai"}
omar = {"leo", "kai", "tess", "zoe"}

mutual = maya ___ omar
suggestions = omar ___ maya
print(sorted(mutual))
print(sorted(suggestions))
print(len(maya ___ omar))

# 👉 replace ___ with &
# 👉 replace ___ with -
# 👉 replace ___ with |

# ✅ Expected output:
# ['kai', 'leo']
# ['tess', 'zoe']
# 6

On your own: visitors on two days

A site logged its visitors on two days, with repeats: monday = ["ana", "ben", "ana", "cara", "dev", "ben"] and tuesday = ["ben", "eve", "dev", "eve", "fay"]. Print how many different visitors came each day, how many came on both days, and a sorted list of those who came only on Monday: four and four, two, and Ana and Cara. Then compare with this solution:

monday = ["ana", "ben", "ana", "cara", "dev", "ben"]
tuesday = ["ben", "eve", "dev", "eve", "fay"]

mon = set(monday)
tue = set(tuesday)
print(len(mon), len(tue))
print(len(mon & tue))
print(sorted(mon - tue))

# ✅ Expected output:
# 4 4
# 2
# ['ana', 'cara']

Making each list a set once does all the de-duplicating, and the operators answer the questions in one line each. sorted() keeps the last line the same on every run.

Practice quiz

What does len({1, 2, 2, 3, 3, 3}) return?

  • 6
  • 3
  • 1
  • 2

Answer: 3. A set keeps one of each value, so it holds 1, 2 and 3.

x = {}. What is type(x)?

  • set
  • list
  • dict
  • tuple

Answer: dict. Empty braces make a dictionary. An empty set is written set().

What does {1, 2, 3} & {2, 3, 4} give?

  • {2, 3}
  • {1, 2, 3, 4}
  • {1, 4}
  • {1}

Answer: {2, 3}. & keeps the values that are in both sets.

tags = {"a"}. What does tags.remove("b") do?

  • Nothing
  • Returns None
  • Removes "a"
  • Stops with KeyError: 'b'

Answer: Stops with KeyError: 'b'. remove() needs the value to be there. discard() is the one that does nothing when it isn't.

Which of these can't go in a set?

  • "hello"
  • 42
  • [1, 2]
  • (1, 2)

Answer: [1, 2]. A list can change, so it isn't hashable: adding one stops with a TypeError that says unhashable type: 'list'.

How many items does {1, True, 1.0} hold?

  • 3
  • 1
  • 2
  • An error

Answer: 1. 1, True and 1.0 are equal, and a set keeps one of each equal value.

colors = {"red", "blue"}. What does colors[0] do?

  • Returns "red"
  • Returns "blue"
  • Returns None
  • Stops with TypeError: 'set' object is not subscriptable

Answer: Stops with TypeError: 'set' object is not subscriptable. A set has no positions, so it can't be indexed.

a = {1, 2, 3} and b = {3, 4}. What is a - b?

  • {1, 2}
  • {4}
  • {1, 2, 4}
  • {3}

Answer: {1, 2}. a - b keeps the values of a that aren't in b.

Continue this course

Frequently asked questions

Is a Python set the same as a set in maths?

Very nearly: no duplicates, no order, and union, intersection and difference mean what they mean in maths. The differences are practical ones. Every member must be hashable, and a set can change after it's made, unless it's a frozenset.

When should I use a list instead of a set?

When order or position matters, or the same value can appear more than once: a queue, a history, scores in the order they came. Use a set when the questions are "is it there?" and "how many different ones are there?".

Related lessons