Module 4 · Beginner · Lists, dictionaries, sets and tuples

Python sets and set operations, with examples

Python sets for beginners: create sets, add and remove items, remove duplicates, and union, intersection and difference, with fast membership tests.

By theprogrammers team · · 8 min read

Two WhatsApp groups, "College friends" and "Cricket team". Who's in both? Who's in the cricket team but not your college group? How many different people are there across both? These are questions about groups of unique items, and Python sets answer each of them in one short line.

A set is a collection with no duplicates and no order. That makes it the quickest way to remove repeats from a list, to check whether something is present, and to compare two groups. This lesson covers creating sets, changing them, and the set operations (union, intersection and difference) with examples.

What you need first: Python lists and Python tuples.

Key terms

  • Set: an unordered collection of unique items, written with curly brackets: {"Ahana", "Rohan"}.
  • Element: one item in a set. The maths word for it.
  • Union: everything that is in either set (or both).
  • Intersection: only what is in both sets.
  • Difference: what is in the first set but not the second.
  • Membership test: checking whether a value is in a collection, with in.

How to create a set in Python

fruits = {"mango", "apple", "mango", "guava"}
print(fruits)
print(len(fruits))

The duplicate "mango" is dropped, so len gives 3. The order the items print in can differ between runs and computers, because sets don't keep order. For that reason this lesson doesn't show the printed set: yours may look different, and that's correct.

Two things to know:

  • {} makes an empty dictionary, not a set. An empty set is set().
  • set() turns any collection into a set, which removes its duplicates.
empty = set()
print(type(empty), type({}))

letters = set("banana")
print(sorted(letters))
<class 'set'> <class 'dict'>
['a', 'b', 'n']

sorted() turns the set into a sorted list, which is the easy way to print a set in a fixed order.

What can go in a set

Set items must be hashable: numbers, strings and tuples are fine, but lists and dictionaries aren't, because they can change.

ok = {1, "two", (3, 4)}
bad = {[1, 2]}
TypeError: unhashable type: 'list'

Removing duplicates from a list

This is the most common use of sets in everyday code:

city_visits = ["Pune", "Delhi", "Pune", "Goa", "Delhi", "Pune"]
unique_cities = set(city_visits)
print(len(city_visits), len(unique_cities))
print(sorted(unique_cities))
6 3
['Delhi', 'Goa', 'Pune']

If you need to keep the original order, list(dict.fromkeys(city_visits)) removes duplicates and keeps the first appearance of each.

Adding and removing items

tags = {"python", "data"}
tags.add("ml")
tags.add("python")          # already there: nothing happens
tags.update(["sql", "excel"])
tags.discard("excel")
tags.discard("java")        # not there: no error
print(sorted(tags))
['data', 'ml', 'python', 'sql']
MethodDoesIf the item is missing
add(x)Adds one itemAdds it
update(items)Adds several itemsAdds them
remove(x)Removes xRaises KeyError
discard(x)Removes xDoes nothing
pop()Removes and returns an item, which one isn't predictableRaises KeyError if empty
clear()Empties the set

Prefer discard when you don't care whether the item was there.

Sets have no indexes. tags[0] raises TypeError: 'set' object is not subscriptable. If you need positions, use a list.

Set operations: union, intersection, difference

Back to the two groups:

college = {"Ahana", "Rohan", "Meera", "Kabir"}
cricket = {"Rohan", "Kabir", "Dev", "Sara"}

print(sorted(college | cricket))     # union: in either group
print(sorted(college & cricket))     # intersection: in both
print(sorted(cricket - college))     # difference: cricket but not college
print(sorted(college ^ cricket))     # symmetric difference: in exactly one
['Ahana', 'Dev', 'Kabir', 'Meera', 'Rohan', 'Sara']
['Kabir', 'Rohan']
['Dev', 'Sara']
['Ahana', 'Dev', 'Meera', 'Sara']
OperatorMethodRead asResult
a | ba.union(b)a union bIn a or b
a & ba.intersection(b)a intersect bIn both
a - ba.difference(b)a minus bIn a, not in b
a ^ ba.symmetric_difference(b)a xor bIn one but not both

Order matters for difference: cricket - college is {Dev, Sara}, but college - cricket is {Ahana, Meera}.

The method versions accept any collection, not only sets: college.union(["Tanvi"]) works, but college | ["Tanvi"] raises a TypeError.

Subsets and supersets

required = {"python", "sql"}
skills = {"python", "sql", "excel", "pandas"}
print(required <= skills)            # is every required skill in skills?
print(required.issubset(skills))
print(skills.isdisjoint({"java", "c"}))
True
True
True

isdisjoint is True when the two sets share nothing.

Why "in" is so fast with sets

Checking x in my_list looks at the items one by one. With 1 lakh items, that's up to 1 lakh comparisons. A set uses hashing: it turns the value into a number that points straight to where the value would be stored, so it checks only one or two places, however big the set is.

import time

numbers_list = list(range(1_000_000))
numbers_set = set(numbers_list)

start = time.perf_counter()
for _ in range(100):
    999_999 in numbers_list
list_time = time.perf_counter() - start

start = time.perf_counter()
for _ in range(100):
    999_999 in numbers_set
set_time = time.perf_counter() - start

print(f"Set lookups were about {list_time / set_time:,.0f} times faster")

The exact number depends on your computer, so we don't show one here. Expect the set to be thousands of times faster. In Big-O notation terms, in is O(n) for a list and O(1) on average for a set.

So when you check membership many times, convert the list to a set once, first.

Frozen sets

A frozenset is a set that can't be changed. Because it's fixed, it's hashable and can be a dictionary key or an item in another set:

vowels = frozenset("aeiou")
print("e" in vowels)
print(type(vowels).__name__)
True
frozenset

Set comprehensions

Like list comprehensions, but with curly brackets:

emails = ["ahana@gmail.com", "rohan@yahoo.com", "meera@gmail.com"]
domains = {e.split("@")[1] for e in emails}
print(sorted(domains))
['gmail.com', 'yahoo.com']

More in Python comprehensions.

Where sets are used

  • Data cleaning: finding the unique categories in a column, which pandas does with .unique().
  • Comparing datasets: customer IDs in this month's file but not last month's.
  • Fast lookups: a set of blocked phone numbers checked against every incoming call.
  • Text and NLP: the vocabulary (set of unique words) in a document.

Common mistakes

  • Writing {} for an empty set. That's a dictionary. Use set().
  • Expecting sets to keep order. If order matters, sort the result or use a list.
  • Indexing a set with [0].
  • Putting lists inside a set. Convert them to tuples first.
  • set("hello world") when you meant a set of words. It gives a set of characters. Use set("hello world".split()).

Practice

  1. How many unique values are in [4, 7, 4, 2, 7, 7, 9]?
Show the answer
print(len(set([4, 7, 4, 2, 7, 7, 9])))
4

The unique values are 2, 4, 7 and 9.

  1. Find the students who passed both Maths and Physics, and those who passed Maths only.
maths = {"Ahana", "Rohan", "Meera", "Dev"}
physics = {"Rohan", "Dev", "Sara"}
Show the answer
maths = {"Ahana", "Rohan", "Meera", "Dev"}
physics = {"Rohan", "Dev", "Sara"}
print(sorted(maths & physics))
print(sorted(maths - physics))
['Dev', 'Rohan']
['Ahana', 'Meera']
  1. Check whether two words are made of the same letters (ignoring how many times each appears): "listen" and "silent".
Show the answer
print(set("listen") == set("silent"))
True

Sets ignore counts, so this also says True for "aab" and "abb". For a true anagram check, compare sorted(a) == sorted(b) instead.

  1. Find the words that appear in both sentences, ignoring case.
s1 = "Python is great for data science"
s2 = "Data science needs Python and maths"
Show the answer
s1 = "Python is great for data science"
s2 = "Data science needs Python and maths"
common = set(s1.lower().split()) & set(s2.lower().split())
print(sorted(common))
['data', 'python', 'science']
  1. Is {1, 2} a subset of {1, 2, 3}? Is {1, 2, 3} a subset of itself? Check in Python.
Show the answer
a = {1, 2}
b = {1, 2, 3}
print(a <= b, b <= b, b < b)
True True False

<= means "subset" (it can be equal). < means "proper subset", which must be strictly smaller.

Interview questions

How do you remove duplicates from a list in Python?

list(set(items)) removes duplicates but loses the order. list(dict.fromkeys(items)) removes them and keeps first-appearance order, because dictionaries keep insertion order since Python 3.7.

Why is checking membership faster in a set than in a list?

A set is a hash table: Python hashes the value and jumps straight to the slot where it would be, which takes O(1) time on average. A list has to compare items one by one, which takes O(n).

What is the difference between remove() and discard()?

Both delete an item. remove raises KeyError if the item isn't in the set; discard silently does nothing.

Key takeaways

  • A set holds unique, unordered, hashable items; set() makes an empty one, because {} is a dictionary.
  • set(my_list) removes duplicates; use dict.fromkeys if order matters.
  • | union, & intersection, - difference, ^ in exactly one.
  • x in some_set is far faster than on a list for large collections.
  • Sets can't be indexed, and their print order isn't fixed, so sort them for display.

Frequently asked questions

Are Python sets ordered?

No. A set has no positions, and the order it prints in can change between runs and versions. Dictionaries keep insertion order, but sets don't.

Can a set contain another set?

Not a normal set, because sets are mutable and so not hashable. A frozenset can be put inside a set.

When should I use a set instead of a list?

When you need unique items, fast in checks, or comparisons between groups, and you don't need order or duplicates.

What to learn next

  1. Build sets, lists and dictionaries in one line with Python comprehensions.
  2. Use sets on real text in cleaning and splitting text in Python.
  3. Compare sets with other collections in choosing the right data structure.