Python course menu
Python Sets: Unique Values, Membership and Set Operations
Learn Python sets: store unique values, remove duplicates from a list, add and remove items, fast membership tests, and set operations (union, intersection, difference, symmetric difference).
On this page
A set is an unordered collection of unique values. Adding something that is already there does nothing. Sets are the fastest way to remove duplicates and to check whether a value is present, and they support the union and intersection operations you may remember from maths.
Creating a set#
Use curly braces, or set() to convert another collection:
tags = {"python", "sql", "python", "web"}
print(len(tags), "sql" in tags)3 TrueThe duplicate "python" was stored only once.
Removing duplicates#
The most common use of sets:
emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
unique = set(emails)
print(len(emails), len(unique))
print(sorted(unique))5 3
['a@x.com', 'b@x.com', 'c@x.com']Sets have no order, so printing one directly can show items in any order. sorted() returns them as an ordered list.
If you need to keep the original order while removing duplicates, use a dictionary instead:
nums = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(nums)))[3, 1, 2]Adding and removing#
s = set()
s.add("apple")
s.add("banana")
s.add("apple") # already there: no change
s.discard("cherry") # not there: no error
s.remove("banana")
print(s){'apple'}remove() raises an error if the item is missing; discard() does not:
s = {"apple"}
s.remove("cherry")KeyError: 'cherry'Sets have no indexes, so s[0] is an error. Loop over a set, or convert it to a list.
Set operations#
Who knows Python, SQL, or both?
python_devs = {"Asha", "Ravi", "Meera"}
sql_devs = {"Ravi", "Meera", "John"}
print(sorted(python_devs | sql_devs)) # union: in either
print(sorted(python_devs & sql_devs)) # intersection: in both
print(sorted(python_devs - sql_devs)) # difference: only in the first
print(sorted(python_devs ^ sql_devs)) # symmetric difference: in exactly one['Asha', 'John', 'Meera', 'Ravi']
['Meera', 'Ravi']
['Asha']
['Asha', 'John']Subset and overlap checks:
print({1, 2} <= {1, 2, 3}, {1, 2, 3} >= {3}, {1, 2}.isdisjoint({3, 4}))True True TrueFast membership tests#
Checking x in some_set is very fast, even with millions of items, because sets use hashing. Checking x in some_list has to look through the list item by item. If you test membership many times, convert to a set first.
Only immutable items#
Set items must be hashable (immutable): numbers, strings and tuples work; lists and dictionaries do not:
s = {[1, 2]}TypeError: unhashable type: 'list'Common mistakes#
Practice#
Practice exercise
Given words = ["apple", "banana", "apple", "cherry", "banana", "apple"], find the words that appear more than once, printed as a sorted list.
Show hint
Keep two sets: seen and dupes. If a word is already in seen, add it to dupes.
Show solution
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
seen = set()
dupes = set()
for w in words:
if w in seen:
dupes.add(w)
seen.add(w)
print(sorted(dupes))['apple', 'banana']Using a set for dupes means "apple" is recorded once even though it repeats twice.
Key takeaway#
Finished this lesson?