Advance Python - III
Sets in Python
A Set in Python is an unordered collection of unique items that is iterable, mutable, and cannot contain duplicate elements.
Sets are created using curly braces {} with comma-separated values.
The main advantage of using a set over a list is its efficient membership testing. Sets use an underlying data structure called a hash table, which makes checking whether an element exists very fast. However, because sets are unordered, you cannot access elements by index like you can with lists.
Examples of Sets
Let’s create a simple set and check its type:
brands = {"Nike", "Adidas", "Puma"}
print(type(brands))
Output:
<class 'set'>
Creating Sets Using the set() Constructor
The set() function can convert other iterable types (like lists or strings) into a set.
# Typecasting list to set
colors = set(["red", "blue", "green"])
print(colors)
# Adding an element to the set
colors.add("yellow")
print(colors)
Output:
{'green', 'red', 'blue'}
{'yellow', 'green', 'red', 'blue'}
Frozen Sets
A frozen set is an immutable version of a set. Once created, you cannot add or remove elements from it. You create it using the frozenset() function.
If no arguments are passed, it returns an empty frozenset.
# Regular set
fruit_set = set(["apple", "banana", "cherry"])
print("Regular Set:")
print(fruit_set)
# Frozen set
frozen_fruit = frozenset(["mango", "kiwi", "pineapple"])
print("\nFrozen Set:")
print(frozen_fruit)
# Uncommenting the following line would cause an error
# frozen_fruit.add("papaya")
Output:
Regular Set:
{'cherry', 'apple', 'banana'}
Frozen Set:
frozenset({'pineapple', 'mango', 'kiwi'})
👀Optional Knowledge :)
Internal Working of Sets
Python sets are implemented using hash tables. When multiple elements produce the same hash, Python handles it via mechanisms like linked lists or other collision-resolution strategies. Internally, sets are implemented using dictionaries, where the set elements are stored as dictionary keys with dummy values.
Methods for Sets
Adding Elements to a Set
You can add elements using the .add() method.
# Creating a set
team = {"Alice", "Bob", "Charlie"}
print("Team:", team)
# Add a new member
team.add("Diana")
# Add numbers to the set
for i in range(10, 13):
team.add(i)
print("\nSet after adding elements:", team)
Output:
Team: {'Bob', 'Alice', 'Charlie'}
Set after adding elements: {'Diana', 10, 11, 12, 'Bob', 'Alice', 'Charlie'}
Union Operation on Sets
You can combine two sets using the union() method or the | operator. Duplicate elements are automatically removed.
flowers = {"rose", "tulip"}
shrubs = {"hibiscus", "bougainvillea"}
trees = {"oak", "pine"}
# Using union() method
garden = flowers.union(shrubs)
print("Union using union() method:")
print(garden)
# Using | operator
garden = flowers | trees
print("\nUnion using | operator:")
print(garden)
Output:
Union using union() method:
{'hibiscus', 'rose', 'tulip', 'bougainvillea'}
Union using | operator:
{'pine', 'oak', 'rose', 'tulip'}
Intersection Operation on Sets
The intersection() method or & operator returns elements common to both sets.
odds = {1, 3, 5, 7}
evens = {2, 4, 6, 8}
mix = {3, 6, 9}
# Using intersection() method
common = odds.intersection(mix)
print("Intersection using intersection() method:")
print(common)
# Using & operator
common = evens & mix
print("\nIntersection using & operator:")
print(common)
Output:
Intersection using intersection() method:
{3}
Intersection using & operator:
{6}
Difference of Sets in Python
The difference() method or - operator finds elements present in one set but not the other.
set_a = {10, 20, 30, 40}
set_b = {30, 40, 50, 60}
# Using difference() method
diff = set_a.difference(set_b)
print("Difference using difference() method:")
print(diff)
# Using - operator
diff = set_b - set_a
print("\nDifference using - operator:")
print(diff)
Output:
Difference using difference() method:
{10, 20}
Difference using - operator:
{50, 60}
Clearing a Set
Use clear() to remove all elements from a set.
numbers = {100, 200, 300, 400}
print("Original Set:")
print(numbers)
# Clear the set
numbers.clear()
print("\nSet after clear():")
print(numbers)
Output:
Original Set:
{200, 100, 400, 300}
Set after clear():
set()
Set Operators
| Operator | Description |
|---|---|
key in s |
Checks if key is in the set |
key not in s |
Checks if key is not in the set |
s1 == s2 |
Checks if both sets are equal |
s1 != s2 |
Checks if sets are not equal |
s1 <= s2 |
Checks if s1 is a subset of s2 |
s1 < s2 |
Checks if s1 is a proper subset of s2 |
s1 >= s2 |
Checks if s1 is a superset of s2 |
s1 > s2 |
Checks if s1 is a proper superset of s2 |
s1 | s2 |
Union of s1 and s2 |
s1 & s2 |
Intersection of s1 and s2 |
s1 - s2 |
Elements in s1 but not in s2 |
s1 ^ s2 |
Elements in s1 or s2, but not both |