Introduction to Sets in Python
Introduction to Sets in Python
Python
Sets are unordered collections of unique elements for fast data
handling.
by Raymart Faller
Creating Sets in Python
Empty Set
Use set() to create an empty set; not curly braces.
From List
Convert list with duplicates to set to keep unique items.
From String
Create set of unique characters from a string.
Set Comprehension
Generate sets dynamically with conditions.
Basic Set Operations
Membership Test Length
Check if element exists in a set quickly. Count how many unique elements the set contains.
Add a single new item to the set. Add multiple items from list or other iterable.
remove(element) discard(element)
Remove an element; raises error if missing. Remove an element if present; no error if missing.
Union Intersection
Combine two sets with no Get common elements with & or
duplicates using | or union(). intersection().
Set Algebra: Difference & Symmetric
Difference
Difference (-) Symmetric Difference (^)
Elements in one set but not the other. Elements in either set, but not both.