More Built-in Container Classes

Introduction to Container Class: set

Definition of a Set

  • Represents a mathematical set

  • An unordered collection of non-identical items

  • Supports operations such as set membership, union, intersection, and difference

  • Curly braces {} are used to define sets

  • Duplicate values are ignored

Example Applications

  • Removing Duplicates from a List:

    • Example code: lst = [22, 23, 22, 23, 25]

    • Converts to set to remove duplicates: list(set(lst)) returns [25, 22, 23]

Special Cases

  • Empty Set:

    • Declared as s = {}

    • Type check: type(s) returns <class 'set'>

Distinction between Set and Dict

  • Question: How does Python differentiate between a set object and a dict object?


Set Operators

Basic Operators and Examples

  • Membership Check: 28 in ages returns True

  • Length: len(ages2) gives 3

  • Equality Check: ages == ages2 yields False

  • Subsetting:

    • ages <= ages2 returns False

    • {22, 25} < ages2 yields True

Set Operations

  • Union: ages | ages2 returns {22, 23, 25, 28}

  • Intersection: ages & ages2 results in {25, 22}

  • Difference: ages - ages2 gives {28}

  • Symmetric Difference: ages ^ ages2 results in {28, 23}

Operation Explanations

  • s == t: True if sets contain the same elements, else False

  • s != t: True if sets do not contain the same elements, else False

  • s <= t: True if all elements of s are in t, else False

  • s < t: True if s <= t and s is not equal to t


Set Methods

Common Set Methods

  • Adding Items: ages.add(30) modifies ages to {25, 28, 30, 22}

  • Removing Items: ages.remove(25) modifies ages to {28, 30, 22}

  • Clearing a Set: ages.clear() results in set()

Mutability of Sets

  • Note that sets are mutable, allowing modification post-creation.