Python Tutorial 0/52 lessons ~6 min read Lesson 19

    Sets

    Sets are unordered collections of unique, hashable items — O(1) membership, union, intersection.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Sets are unordered collections of unique, hashable items — O(1) membership, union, intersection. Perfect for deduplication.

    Understanding the topic

    Core concepts to understand:

    • {1, 2, 3} or set().
    • x in s is O(1) avg.
    • Operations: | union, & intersect, - diff.
    • frozenset is the immutable variant.

    Syntax reference

    Visual flow / code:

    python
    a = {1, 2, 3}
    b = {3, 4, 5}
    print(a | b) # {1,2,3,4,5}
    print(a & b) # {3}
    print(a - b) # {1, 2}
    print(a ^ b) # {1,2,4,5} symmetric diff
    # Deduplicate
    unique = set([1, 1, 2, 2, 3]) # {1,2,3}
    # Membership test (fast)
    if user_id in admin_set: ...

    Execution workflow

    1Sets Workflow
    1 / 4

    {1, 2, 3} or set()

    {1, 2, 3} or set().

    Real-world use

    Sets are the go-to for membership tests on large datasets. Replace x in big_list (O(n)) with x in big_set (O(1)).

    Best practices

    • Use sets for membership tests.
    • Set ops for algebra over collections.
    • frozenset for set-of-sets.

    Common mistakes

    • Set elements must be hashable — no lists/dicts inside.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionSet vs list lookup time?+

    Answer

    Membership tests on a set are O(1) on average because sets use a hash table, while a list needs an O(n) linear scan. For small collections the difference is negligible, but it grows with size. The set requires hashable items and building one costs O(n), so it pays off when you do many lookups.

    Follow-up

    What is the worst case for a set lookup?
    2IntermediateQuestionWhat's a frozenset?+

    Answer

    A frozenset is an immutable, hashable version of a set. Because it cannot change, it can be used as a dictionary key or as an element of another set, which regular sets cannot. It supports the same read-only operations such as union and intersection but has no add or remove.
    3IntermediateQuestionWhy must set items be hashable?+

    Answer

    Sets use each item's hash to decide where it is stored, and equal items must have equal hashes so lookups can find them. Mutable objects like lists can change in ways that alter equality and hash, which would break the table, so they are unhashable. Hashable objects must define __hash__ consistent with __eq__.

    Follow-up

    What rule connects __eq__ and __hash__?

    Summary

    In summary: O(1) membership, dedup, set algebra. Hashable items only.

    Ready to mark this lesson complete?Track your journey across the entire course.