Module lessons (4/4)
Sets
Unique element collections, set algebra (& | - ^), and O(1) membership checks.
What you'll learn in this lesson
- Eliminate duplicates with
set(...)and perform membership checksx in itemsin constant timeO(1). - Apply set algebra (
|union,&intersection,-difference,^symmetric difference). - Distinguish the empty dictionary
{}from the empty setset()and choose betweenremove()vsdiscard().
Overview
A set is an unordered collection of unique and hashable elements. When you want to quickly answer the question "has this item been seen before?" or calculate what two lists have in common, a set reduces the check times from linear O(n) to constant O(1).
Just like the keys of a dict, the elements of a set are indexed via hash table: no duplicates allowed, no positional indexing (s[0] lifts TypeError), and lightning-fast performance on in. For immutable sets (e.g. used in turn within other sets or as dict keys) frozenset exists.
Sections covered in this lesson
- 1The mental model: mathematical bag based on hash table
- 2Deduplication, safe mutation and set algebra
- 3Quick check
- 4Test yourself
Unlock "Sets" and the full Python Course curriculum
Unique element collections, set algebra (& | - ^), and O(1) membership checks.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.