Sets in Python
Python tutorial · PySpark.in
Sets
A set in Python is a collection of unique, unordered,mutable and unique elements. Sets are mainly used when you want to remove duplicates or perform mathematical operations like union, intersection, etc.
What makes Sets Special
No duplicates allowed
-
Unordered (no indexing)
-
Mutable (you can add/remove items)
-
Fast for membership checks (like
in) -
Performs math operations easily
Creating a Set
Defining a set using curly braces {} or the set() function.
Note:
Accessing Set Items
Sets cannot be accessed using indexes; they can only be looped through.
Adding Elements to a Set
add() – add a single element
Adds a single new element to the set.
update() – add multiple elements
Adds multiple elements (from lists, sets, or iterables) to the set.
Removing Elements
Deletes a specific item from the set but raises an error if the item doesn't exist.
Set Operations (Math Operations)
1. Union (A ∪ B)
Returns all unique elements from both sets combined.
2. Intersection (A ∩ B)
Returns elements that are common to both sets.
3. Difference (A – B)
Returns elements present in the first set but not in the second.
4. Symmetric Difference
Returns elements that are in either set but not in both.
Checking Membership
Checks whether a value exists inside a set using in.
Example: Remove Duplicates from a List
Converts a list into a set to eliminate duplicate values.
Useful Set Methods
Set Methods in Python
Method | Description |
|---|---|
add() | Add one item |
remove() | Remove item (error if missing) |
discard() | Remove item (no error) |
pop() | Remove random item |
clear() | Remove all items |
union() | Combine sets |
intersection() | Common elements |
difference() | Items only in one set |
symmetric_difference() | Items not common |
issubset() | Checks if A is subset of B |
issuperset() | Checks if A is superset of B |
isdisjoint() | No common elements |
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges