Module 8 · Python Data Structures — topic 12 of 22
Sets
Sets are unordered collections of unique items with very fast membership tests. Learn how to create sets (including the empty set), add and remove items, and what can be stored in a set.
Learning objectives
- Create sets and remove duplicates with set()
- Add and remove items with add, discard and remove
- Explain hashability and why sets are fast
Definition
Sets are unordered collections of unique items with very fast membership tests. Learn how to create sets (including the empty set), add and remove items, and what can be stored in a set.
Introduction
A set is a collection of unique items with no particular order. Adding an item that is already present has no effect. Sets are written with braces: {"python", "java"}.
Why it matters
Sets answer “have I seen this before?” and “what are the distinct values?” better than any other structure. Removing duplicate emails, tracking visited pages or checking whether a word is in a vocabulary of thousands are natural set tasks.
Detailed explanation
Sets keep only one copy of each value: set([3, 1, 3, 2]) is {1, 2, 3}.
Sets are unordered: they have no indexes and no slicing, and the printed order isn’t guaranteed. Use sorted(s) to get a list in order.
{} creates an empty dictionary, not a set. Use set() for an empty set.
add(x) inserts an item; discard(x) removes it if present without error; remove(x) removes it but raises KeyError if absent; pop() removes an arbitrary item; clear() empties the set.
Items must be hashable, which in practice means immutable: numbers, strings and tuples of immutable values are fine, but lists and dictionaries can’t be set members.
Sets use hashing to find items, so x in a_set is fast even with millions of items, whereas x in a_list checks items one by one.
frozenset is an immutable version of a set that can itself be a set member or dictionary key.
Syntax
- Braces with values make a set.
- set() makes an empty set; {} is a dict.
- add and discard change the set.
Code examples
Uniqueness
5 3 ['a@x.com', 'b@x.com', 'c@x.com'] dict set
Adding and removing
['about', 'home'] remove() raises KeyError for a missing item
More examples
Tracking first-time visitors
Unique visitors: 4 Order of first visits: ['u1', 'u2', 'u3', 'u4'] TypeError: cannot use 'list' as a set element (unhashable type: 'list') True
Step-by-step explanation
- seen is checked before adding, so each user is recorded once.
- first_visits keeps the order in which new users appeared, which a set alone can’t do.
- A list can’t be a set member because it is mutable (unhashable).
- Tuples are hashable, and duplicate tuples collapse to one.
Expected output
Running “Tracking first-time visitors” prints exactly:
Practical applications
- Web analytics count unique visitors with sets.
- Spell checkers test words against a set of known words.
- Crawlers keep a set of visited URLs to avoid loops.
Best practices
- Use sets for uniqueness and fast membership.
- Use discard() when the item may be absent.
- Sort a set before displaying it.
Common mistakes
Creating an empty set with {}
Avoid
Prefer
{} is an empty dictionary, which has no add method.
Indexing a set
Avoid
Prefer
Sets have no order or indexes.
Key takeaways
- Sets hold unique, hashable items in no particular order.
- set() is an empty set; {} is an empty dict.
- add, discard, remove and pop change a set; in is fast.
Try it yourself
- 1Count the distinct words in a sentence using a set (ignore case).
- 2Given two lists of roll numbers, check quickly whether a given roll number is in either.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?