Skip to main content
Module 3 · Lesson 4 of 412/36 in the course~14 min
Module lessons (4/4)

Sets

Lesson preview5 hands-on exercises readyPython Course · Module 3 — Data structures

Unique element collections, set algebra (& | - ^), and O(1) membership checks.

What you'll learn in this lesson

  • Eliminate duplicates with set(...) and perform membership checks x in items in constant time O(1).
  • Apply set algebra (| union, & intersection, - difference, ^ symmetric difference).
  • Distinguish the empty dictionary {} from the empty set set() and choose between remove() vs discard().

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

  1. 1The mental model: mathematical bag based on hash table
  2. 2Deduplication, safe mutation and set algebra
  3. 3Quick check
  4. 4Test yourself
Pro Lesson · Module 3 — Data structures

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.