Introduction to Python Sets
Python sets are unordered collections that store only unique values. They are widely used when you need fast membership testing, duplicate removal and mathematical operations like union or intersection.
Unlike lists or tuples, sets do not maintain order and do not allow duplicate elements. This makes them highly efficient for data filtering and comparison tasks.
Sets are mutable, meaning you can add or remove elements after creation, but the elements themselves must be immutable types.
Next, let’s cover the foundation concepts of Python sets before moving to operations and methods.
1. Foundation Concepts: Python Sets
Before working with set methods and operators, it is important to understand how sets are created and how they behave. These basic concepts help build a strong foundation for everything else in Python sets.
1.1) Python Set – Creation Methods & Rules (set() vs {})
Python provides two main ways to create a set. You can either use curly braces {} directly or use the set() constructor.
Example:
s1 = {1, 2, 3}
s2 = set([1, 2, 3, 3])
print(s1)
print(s2)
Duplicate values are automatically removed in sets.
Learn More: Python Set – Creation Methods & Rules (set() vs {})
1.2) Python set() Constructor
The set() constructor is useful when you want to convert another iterable like a list, tuple, or string into a set.
s = set("python")
print(s)
Converts an iterable into a set of unique values.
Learn More: Python set() Constructor: Create Sets from Iterables | Syntax, Examples & Use Cases
1.3) Accessing Elements in Python Sets
Unlike lists or tuples, sets do not store elements in a fixed order. Because of this, indexing is not supported.
s = {10, 20, 30}
# print(s[0]) ❌ Not allowed
Sets do not support indexing because they are unordered.
Learn More: Accessing Elements in Python Sets: Syntax, Examples & Use Cases
Now let’s look at basic operations and utilities available in Python sets.
2. Basic Operations & Utilities: Python Sets
Once a set is created, the next step is learning how to work with it. Python provides simple built-in tools to check size, test membership, and even remove an entire set when it is no longer needed.
2.1) Python Sets – len() Method
The len() function is used to count how many unique elements are present in a set.
s = {1, 2, 3, 4}
print(len(s))
👉 Returns the total number of unique elements.
Learn More: Python len() Function with Sets: Count Set Elements | Syntax, Examples & Use Cases
2.2) Python Set – del Statement
The del statement is used when you want to completely remove a set from memory.
s = {1, 2, 3}
del s
👉 Completely deletes the set from memory.
Learn More: Python Set – del Statement: Delete Sets or Remove References
2.3) Python Set – Membership Testing (in / not in)
Membership operators help check whether a value exists inside a set. This is one of the fastest operations in Python sets.
s = {1, 2, 3}
print(2 in s)
print(5 not in s)
👉 in checks if an element exists, while not in checks if it is missing.
Learn More: Python Sets – Membership Testing: Check Elements Using [in] and [not in] | Syntax, Usage & Examples
Next, we will explore how Python sets handle core operations and processing logic.
3. Core Set Processing Logic: Python Sets
Once the basics are clear, the next step is learning how sets interact with each other. Python sets support powerful operations like combining data, finding common values, and filtering unique elements.
3.1) Python Set Operators
Set operators are used to compare and combine two sets in different ways.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(a ^ b) # Symmetric Difference
👉 Union combines values, intersection finds common elements, difference removes overlaps, and symmetric difference keeps only non-matching values.
Learn More: Python Set Operators: Union, Intersection, Difference & Symmetric Difference
Now let’s move to some advanced concepts of Python sets.
4. Advanced Set Concepts: Python Sets
After learning the basic operations, you can move to more advanced set features. These concepts make sets more flexible and useful in real-world programming.
4.1) Set Comprehension
Set comprehension is a short and clean way to create sets using loops and conditions in a single line.
s = {x for x in range(10) if x % 2 == 0}
print(s)
👉 Creates a set of even numbers from 0 to 9.
Learn More: Python Set Comprehension: Create Sets Using Short and Clean Expressions | Syntax, Examples & Use Cases
4.2) frozenset (Immutable Set)
A frozenset is similar to a normal set, but its elements cannot be changed after creation.
fs = frozenset([1, 2, 3])
print(fs)
👉 Useful when you need a fixed set that should not be modified.
Learn More: Python frozenset: Syntax, Examples & Use Cases
Finally, let’s understand the important built-in methods available for Python sets.
5. Python Set Methods
Python set methods are built-in methods used to perform different operations on sets, such as adding elements, removing values, combining sets, and comparing data. These methods can be grouped based on their purpose, making them easier to understand and use.
Below are the main categories of Python set methods along with the functions included under each category.
5.1) Add / Insert Operations
These methods are used when new elements need to be added to a set. They help expand the set while still maintaining unique values.
i) add(): Adds a single element to the set.
5.2) Remove / Delete Operations
These methods are useful for deleting elements from a set. Some remove a specific value, while others can clear the entire set.
i) remove(): Removes a specific element from the set and raises an error if it is not found.
ii) discard(): Removes a specific element without raising an error if it does not exist.
iii) pop(): Removes and returns a random element from the set.
iv) clear(): Removes all elements from the set and makes it empty.
5.3) Copy & Merge Operations
These methods help create duplicates of existing sets or combine multiple sets into one collection.
i) copy(): Creates a shallow copy of the set.
ii) update(): Adds elements from another set or iterable into the current set.
iii) union(): Returns a new set containing elements from both sets.
5.4) Comparison / Logical Methods
These methods are used to compare sets and check relationships such as common elements, subset conditions, or unique differences.
i) intersection(): Returns the common elements shared between sets.
ii) difference(): Returns elements that are present only in the first set.
iii) symmetric_difference(): Returns elements that exist in either set but not in both.
iv) issubset(): Checks whether all elements of one set exist in another set.
v) issuperset(): Checks whether a set contains all elements of another set.
vi) isdisjoint(): Checks whether two sets have no common elements.
5.5) In-place Update Variants
These methods directly modify the existing set instead of returning a new one after performing operations.
i) intersection_update(): Keeps only the common elements in the current set.
ii) difference_update(): Removes elements from the current set that also exist in another set.
iii) symmetric_difference_update(): Updates the set with elements that are not common between both sets.
6. Real-World Use Cases of Python Sets
Python sets are commonly used in situations where duplicate values need to be removed or fast lookups are required.
- Removing duplicate values from a list or dataset
- Checking whether a value exists in a collection quickly
- Finding common values between two groups of data
- Comparing survey responses or user preferences
- Cleaning data before analysis or machine learning tasks
7. Common Errors in Python Sets
While sets are simple to use, there are a few common mistakes that beginners often make.
- Trying to access set elements using indexing like my_set[0]
- Using remove() on an element that does not exist in the set
- Expecting sets to keep elements in the same order every time
- Adding mutable values like lists or dictionaries inside a set
- Forgetting that duplicate values are automatically removed
8. Python Set vs List vs Tuple
| Feature | Set | List | Tuple |
|---|---|---|---|
| Order Maintained | No | Yes | Yes |
| Allows Duplicates | No | Yes | Yes |
| Mutable | Yes | Yes | No |
| Supports Indexing | No | Yes | Yes |
| Uses Curly Braces | Yes | No | No |
| Best For | Unique values | Ordered collections | Fixed collections |
Sets are useful when only unique values are needed. Lists work better when order matters, while tuples are ideal for fixed data that should not change.
9. Category-wise Methods Table
| Sl No. | Category | Method | Purpose |
|---|---|---|---|
| 1 | Add / Insert Operations | add() | Adds a single element to the set |
| 2 | Remove / Delete Operations | remove() | Removes a specific element; raises an error if not found |
| 3 | Remove / Delete Operations | discard() | Removes a specific element without raising an error if missing |
| 4 | Remove / Delete Operations | pop() | Removes and returns a random element from the set |
| 5 | Remove / Delete Operations | clear() | Removes all elements from the set |
| 6 | Set Mathematical Operations | copy() | Creates a shallow copy of the set |
| 7 | Set Mathematical Operations | update() | Adds elements from another iterable or set into the current set |
| 8 | Set Mathematical Operations | union() | Returns a new set containing elements from both sets |
| 9 | Set Relationship Checking | intersection() | Returns common elements between sets |
| 10 | Set Relationship Checking | difference() | Returns elements present only in the first set |
| 11 | Set Relationship Checking | symmetric_difference() | Returns elements that are present in either set but not both |
| 12 | Set Relationship Checking | issubset() | Checks whether one set is fully contained within another |
| 13 | Set Relationship Checking | issuperset() | Checks whether a set fully contains another set |
| 14 | Set Relationship Checking | isdisjoint() | Checks whether two sets have no common elements |
| 15 | In-place Update Operations | intersection_update() | Updates the current set with only common elements |
| 16 | In-place Update Operations | difference_update() | Removes common elements from the current set |
| 17 | In-place Update Operations | symmetric_difference_update() | Updates the current set with non-common elements only |