Python Sets

Python sets are unordered collections of unique items. A set automatically discards duplicates and makes it very fast to check whether a value is present. Sets are written with curly braces, or created with the set() function.

Create a Set

Duplicates disappear as soon as the set is created. Because sets are unordered, you cannot access items by index. Note that {} creates an empty dictionary, so use set() for an empty set.

tags = {"python", "web", "python", "data"}
print(len(tags))
print("web" in tags)

empty = set()
print(type(empty), type({}))
3
True
<class 'set'> <class 'dict'>

Remove Duplicates from a List

Converting a list to a set and back is the quickest way to remove duplicates. If you need to keep the original order, dict.fromkeys() does it.

visits = [3, 1, 3, 2, 1, 5]

print(sorted(set(visits)))
print(list(dict.fromkeys(visits)))
[1, 2, 3, 5]
[3, 1, 2, 5]

Add and Remove Items

add() inserts one item, update() inserts several. remove() raises an error if the item is missing, while discard() quietly does nothing.

skills = {"python"}
skills.add("sql")
skills.update(["git", "docker"])
skills.discard("java")
skills.remove("docker")

print(sorted(skills))
['git', 'python', 'sql']

We print sorted(skills) so the output is predictable. Printing a set of strings directly can show the items in a different order each time the program runs.

Set Operations

Sets support the classic maths operations. Each has an operator and a method form.

team_a = {"Ali", "Sara", "John"}
team_b = {"Sara", "Emma", "John"}

print(sorted(team_a | team_b))   # union: in either
print(sorted(team_a & team_b))   # intersection: in both
print(sorted(team_a - team_b))   # difference: only in a
print(sorted(team_a ^ team_b))   # symmetric difference
['Ali', 'Emma', 'John', 'Sara']
['John', 'Sara']
['Ali']
['Ali', 'Emma']

Subsets and frozenset

issubset() and issuperset() compare whole sets. A frozenset is an immutable set, so it can be used as a dictionary key or stored inside another set.

required = {"python", "sql"}
mine = {"python", "sql", "git"}

print(required.issubset(mine))
print(mine >= required)

fixed = frozenset([1, 2, 3])
print(fixed)
True
True
frozenset({1, 2, 3})

When to Use a Set

  • You need unique values only
  • You check membership (x in collection) often; sets are much faster than lists for this
  • You want to compare groups with union, intersection or difference
  • Order does not matter

Frequently asked questions

How do I remove duplicates from a list in Python?

Use list(set(my_list)) if order does not matter, or list(dict.fromkeys(my_list)) to keep the original order.

How do I create an empty set in Python?

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

Are Python sets ordered?

No. Sets do not keep insertion order and cannot be indexed. Use sorted(my_set) when you need the items in a predictable order.