What are Sets in Python?
Sets in python are built-in data type that represents a collection of unique elements that dont follow any particular order ie. they are unordered unlike lists , and tuples. They are helpful for finding, adding and removing elements. Duplicate elements are automatically eliminated. A set is created using curly brackets {} or by using the set() function.
Sets support a variety of mathematical operations like union , intersection , difference and symmetric difference that are helpful for finding out common or uncommon items between two pairs of sets. They are ideal for situations where unique elements are required .
Characteristics of Sets
- UNORDERED – elements in a set do not follow any particular order due to which slicing or indexing cannot be performed.
- UNIQUE ELEMENTS – sets do not allow duplicate values whenever a set has a duplicate value they get ignored automatically .
- MUTABLE – elements can be added or removed from sets using set operations.
- MEMBERSHIP TESTING – it is easy to check whether an element exists in a set or not using in operator.
How to Create a Set in Python?
You can create a set in two ways:
1. Using curly brackets {} :
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
2. Using the set() constructor:
my_set = set([1, 2, 3, 4, 4, 5])
print(my_set) # Output: {1, 2, 3, 4, 5}
Set Length
The len() function returns the total number of unique elements in the set.
my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # Output: 5
Set Membership
It refers to checking whether an element exists in a set using the in and not in operators.
my_set = {1, 2, 3, 4, 5}
# Check if an element exists in the set
print(3 in my_set) # Output: True
print(6 in my_set) # Output: False
# Check if an element does not exist in the set
print(6 not in my_set) # Output: True
print(2 not in my_set) # Output: False
Set Operations
1. Adding Elements
- Use add() to add a single element to the set.
my_set = {1, 2}
my_set.add(3)
print(my_set) # Output: {1, 2, 3}
- Use update() to add multiple elements.
my_set.update([4, 5, 6])
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
2. Removing Elements
- Use remove() to delete a specific element . It will raise a KeyError if the element doesn’t exist.
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
- Use discard() to remove an element without raising an error if the element doesn’t exist.
my_set.discard(4) # No error, even though 4 is not in the set
- Use pop() to remove and return a random element from the set.
my_set = {1, 2, 3}
print(my_set.pop()) # Output: 1 or 2 or 3 (random)
- Use clear() to remove all elements.
my_set.clear()
print(my_set) # Output: set()
Mathematical Set Operations in Python
Sets are used for mathematical operations that are useful for tasks such as finding similarities or differences.
1. Union
Combines all elements from two sets.
- Using union() method:
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
- Using | operator:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
2. Intersection
Useful for finding out common elements to both sets (common)
- Using intersection() method:
print(set1.intersection(set2)) # Output: {3}
- Using & operator:
print(set1 & set2) # Output: {3}
3. Difference
Elements present in one set but not in another.
- Using difference() method:
print(set1.difference(set2)) # Output: {1, 2}
- Using - operator:
print(set1 - set2) # Output: {1, 2}
4. Symmetric Difference
Helps in finding elements that are unique to each set (not common)
- Using symmetric difference() method:
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}
- Using ^ operator:
print(set1 ^ set2) # Output: {1, 2, 4, 5}
Set Comparison
1. Subset(<=)
Returns True if all the elements of one set exist in another.
set1 = {1, 2}
set2 = {1, 2, 3}
print(set1 <= set2) # Output: True
2. Superset(>=)
Returns True if a set contains all elements of another.
print(set2 >= set1) # Output: True
3. Disjoint Sets
Returns True if two sets have no common elements.
print(set1.isdisjoint({4, 5})) # Output: True
Frozen Sets
A Frozenset is an immutable version of a set . Once it has been created , its elements cannot be modified or changed.
f_set = frozenset([1, 2, 3])
print(f_set) # Output: frozenset({1, 2, 3})
We can use loops to iterate over the elements of a set . However , looping does not follow any particular order.
1. For loop
my_set = {1, 2, 3, 4, 5}
# Loop through the set
for item in my_set:
print(item)
Output ( Order may vary because sets are unordered ):
1
2
3
4
5
2. While loop
my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)
# Process the set using while loop
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
Output ( Order may vary because sets are unordered ):
1
2
3
4
5
3. Nested loops with sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Compare elements in two sets
for item1 in set1:
for item2 in set2:
if item1 == item2:
print(f"Common element: {item1}")
Set Comprehension
It is a way to create sets using a single line of code.
{expression for item in iterable if condition}
- Expression : The value or transformation which is to be included in the set.
- Item : The element to be iterated over.
- Iterable : A collection ( like lists, tuples or range ) that provides the elements.
- Condition : A filter that will be used to include only specific elements.
Conclusion
Sets in python are a powerful tool for working with collections of unique elements. They help us with efficient operations like membership testing and support mathematical operations like union, intersection and difference. Whether to clean up duplicates or compare datasets or ensure uniqueness, sets play a crucial role in Python programming.
Get in touch with us!
Your email address will not be published.