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 setsDuplicate 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 agesreturnsTrueLength:
len(ages2)gives3Equality Check:
ages == ages2yieldsFalseSubsetting:
ages <= ages2returnsFalse{22, 25} < ages2yieldsTrue
Set Operations
Union:
ages | ages2returns{22, 23, 25, 28}Intersection:
ages & ages2results in{25, 22}Difference:
ages - ages2gives{28}Symmetric Difference:
ages ^ ages2results in{28, 23}
Operation Explanations
s == t: True if sets contain the same elements, else Falses != t: True if sets do not contain the same elements, else Falses <= t: True if all elements ofsare int, else Falses < t: True ifs <= tandsis not equal tot
Set Methods
Common Set Methods
Adding Items:
ages.add(30)modifiesagesto{25, 28, 30, 22}Removing Items:
ages.remove(25)modifiesagesto{28, 30, 22}Clearing a Set:
ages.clear()results inset()
Mutability of Sets
Note that sets are mutable, allowing modification post-creation.