Introduction to Sets in
Python
Sets are unordered collections of unique elements for fast data
handling.
They are mutable and automatically remove duplicate entries.
Create sets using curly braces or the set() constructor.
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.
Iteration Not Indexable
Access each element, order is arbitrary since sets Sets don't support indexing or slicing operations.
are unordered.
Adding and Removing Elements
add(element) update(iterable)
Add a single new item to the set. Add multiple items from list or other iterable.
Example: my_set.add(4) Example: my_set.update([4,5,6])
remove(element) discard(element)
Remove an element; raises error if missing. Remove an element if present; no error if missing.
Example: my_set.remove(2) Example: my_set.discard(7)
The pop() method removes and returns an arbitrary element.
Set Algebra: Union and
Intersection
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.
Example: set1 - set2 Example: set1 ^ set2