When working with Python, we often need to store multiple values in a single variable. Python provides different collection data types, such as Lists, Tuples, Dictionaries, and Sets.
In this blog, let's understand Sets in Python, why we use them, and how to perform different operations.
1. What is a Set in Python?
A Set is a built-in collection data type in Python that stores multiple values in a single variable.
The main characteristics of a Set are:
- Unordered: Elements do not have a fixed position.
- Unchangeable elements: You cannot modify an individual element, but you can add or remove elements.
- No duplicates: A Set automatically removes duplicate values.
- Mutable: You can add or remove elements after creating a Set.
2. How to Create a Set
We use curly braces {} to create a Set.
numbers = {10, 20, 30, 40}
print(numbers)
Output:
{40, 10, 20, 30}
Remember: Sets are unordered, so the output order may be different.
3. Creating an Empty Set
There is something important to remember when creating an empty Set.
a = {}
print(type(a))
Output:
<class 'dict'>
Why? Because {} creates an empty dictionary, not an empty Set.
To create an empty Set, use set().
a = set()
print(type(a))
Output:
<class 'set'>
4. Duplicate Values in Sets
One of the most useful features of Sets is that they do not allow duplicate values.
numbers = {10, 20, 30, 10, 20}
print(numbers)
Output:
{10, 20, 30}
Python automatically removes duplicate values.
5. Adding Elements to a Set
We use the add() method to insert a single element.
numbers = {10, 20, 30}
numbers.add(40)
print(numbers)
Output:
{10, 20, 30, 40}
To add multiple elements, use update().
numbers.update([50, 60, 70])
print(numbers)
6. Removing Elements from a Set
Python provides different methods to remove elements.
remove():
Removes an element. If the element does not exist, it raises a KeyError.
numbers = {10, 20, 30}
numbers.remove(20)
print(numbers)
discard():
Removes an element without raising an error if it does not exist.
numbers.discard(50)
print(numbers)
pop():
Removes and returns an arbitrary element.
numbers = {10, 20, 30}
numbers.pop()
print(numbers)
clear():
Removes all elements from the Set.
numbers.clear()
print(numbers)
7. Set Operations
Set operations are one of the most interesting features of Python Sets.
Let's understand them with examples.
Union ( | )
Combines elements from two Sets without duplicates.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
Output:
{1, 2, 3, 4, 5}
Intersection ( & )
Returns only the common elements.
print(a & b)
Output:
{3}
Difference ( - )
Returns elements that exist in the first Set but not in the second Set.
print(a - b)
Output:
{1, 2}
Symmetric Difference ( ^ )
Returns elements that are present in either Set, but not in both.
print(a ^ b)
Output:
{1, 2, 4, 5}
8. Checking Elements in a Set
We can use the in and not in operators to check whether an element exists.
numbers = {10, 20, 30}
print(20 in numbers)
print(50 not in numbers)
Output:
True
True
9. Frozen Sets
Python also provides a collection called frozenset.
A frozenset is an immutable version of a Set. Once created, you cannot add or remove its elements.
numbers = frozenset([10, 20, 30])
print(numbers)
You cannot use methods like add() or remove() on a frozenset.
10. When Should We Use Sets?
Sets are useful in situations like:
- Removing duplicate values from a list.
- Finding common elements between two collections.
- Comparing two groups of data.
- Checking whether an element exists in a collection.
- Performing mathematical set operations.
Example: Removing duplicates from a List
numbers = [10, 20, 10, 30, 20, 40]
unique_numbers = set(numbers)
print(unique_numbers)
Output:
{10, 20, 30, 40}
Conclusion
Python Sets are useful when we need to store unique values and perform operations such as Union, Intersection, Difference, and Symmetric Difference.
Top comments (0)