In Python, a Set is a collection of unique elements. It is mainly used when we want to store multiple values without duplicates.
A set is based on the mathematical concept of sets.
1. What is a Set?
A set is an unordered collection of distinct, hashable objects.
| Property | Description |
|---|---|
| Unordered | Does not guarantee insertion order |
| Unique Elements | Duplicate elements are not allowed |
| No Indexing | Cannot access elements using index positions |
| No Slicing | Slicing operations are not supported |
| No Step Operations | Cannot access elements using step-based indexing |
| Hashable Elements | Elements must be hashable |
| Mutable | Elements can be added or removed after creation |
Example
s = {10, 20, 30, 40}
print(s)
s = {10, 10, 10, 20, 30, 40}
print(s)
Output:
{10, 20, 30, 40}
{10, 20, 30, 40}
Even though we provided duplicate values, Python stores only unique elements.
2. Understanding Hashing and hash()
A hash is an integer value generated by a hashing algorithm.
Python uses hash values to identify and manage elements in a set efficiently.
The hash() function returns the hash value of a hashable object.
Example
print(hash(10))
print(hash("Python"))
print(hash((10, 20, 30)))
Note: Hash values for some objects, especially strings, can differ between Python executions.
A set can store hashable elements such as integers, strings and tuples containing only hashable elements.
Mutable objects like lists and dictionaries cannot be stored directly inside a set.
3. Creating Sets in Python
Python provides different ways to create collections.
| Collection | Syntax | Example |
|---|---|---|
| List | [] | l = [10, 20, 30] |
| Tuple | () | t = (10, 20, 30) |
| Set | {} | s = {10, 20, 30} |
| Dictionary | {} | d = {"a": 10} |
| Empty List | [] | l = [] |
| Empty Tuple | () | t = () |
| Empty Set | set() | s = set() |
| Empty Dictionary | {} | d = {} |
Important: Empty curly braces {} create an empty dictionary, not an empty set.
To create an empty set, use set().
Example
s = set()
print(type(s))
Output:
<class 'set'>
4. Adding Elements to a Set
We use the add() method to insert a single element into a set.
Sets do not support the append() method because they are not ordered collections like lists.
Example
s = set()
s.add(10)
s.add(20)
s.add(30)
s.add(40)
print(s)
Output:
{10, 20, 30, 40}
5. Removing Duplicates from a List Using a Set
Suppose we have a list containing duplicate values.
l1 = [10, 20, 30, 40, 50, 10, 20, 30]
s = set(l1)
print(s)
The set automatically removes duplicate values.
Note: Converting a list to a set does not preserve the original order.
If we want to preserve the original order, we can use dict.fromkeys().
l1 = [10, 20, 30, 40, 50, 10, 20, 30]
l2 = list(dict.fromkeys(l1))
print(l2)
Output:
[10, 20, 30, 40, 50]
6. Creating a Set Using range()
We can create a set using the set() constructor and range() function.
s = set(range(1, 11))
print(s)
Output:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
7. Removing Elements from a Set
Python provides different methods to remove elements from a set.
The two important methods are remove() and discard().
Example
s = set(range(1, 11))
s.remove(5)
print(s)
s.discard(100)
print(s)
Use discard() when you are not sure whether an element exists in the set.
remove() vs discard()
| Feature | remove() | discard() |
|---|---|---|
| Purpose | Removes a specified element | Removes a specified element |
| Element Exists | Removes the element | Removes the element |
| Element Not Exists | Raises KeyError | Does not raise an error |
| Example | s.remove(5) | s.discard(100) |
8. Mathematical Set Operations
Python supports mathematical set operations such as:
- Union
- Intersection
- Difference
- Symmetric Difference
Consider two sets:
s1 = {10, 20, 30, 40}
s2 = {30, 40, 50, 60}
A. Union
Union combines all unique elements from both sets.
print(s1.union(s2))
print(s1 | s2)
Output:
{10, 20, 30, 40, 50, 60}
B. Intersection
Intersection returns only the common elements in both sets.
print(s1.intersection(s2))
print(s1 & s2)
Output:
{30, 40}
C. Difference
Difference returns elements that exist in the first set but not in the second set.
print(s1.difference(s2))
print(s1 - s2)
Output:
{10, 20}
D. Symmetric Difference
Symmetric difference returns elements that are present in either set, but not in both.
print(s1.symmetric_difference(s2))
print(s1 ^ s2)
Output:
{10, 20, 50, 60}
9. Set Comprehension
Set comprehension is a shorter way to create sets using a single expression.
Without Set Comprehension
s = set()
for no in range(1, 11):
s.add(no)
print(s)
With Set Comprehension
s = {no for no in range(1, 11)}
print(s)
Output:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Both approaches produce the same set.
10. Converting a String into a Set
We can convert a string into a set using the set() constructor.
Each character becomes an element, and duplicate characters are removed.
Example
s = set("megalraja")
print(s)
The output contains only unique characters. Since sets are unordered, the character order is not guaranteed.
If we want the characters in sorted order, we can use sorted().
s = set("megalraja")
print(sorted(s))
Output:
['a', 'e', 'g', 'j', 'l', 'm', 'r']
Remember: sorted() returns a list, not a set.
We can use the in and not in operators to check whether an element exists in a set.
Example
s = set("megalraja")
print('g' in s)
print('h' in s)
Output:
True
False
Top comments (0)