-
Hajipur, Bihar, 844101
In Python, sets are a built-in data structure used to store unique and unordered elements. Unlike lists or tuples, sets automatically remove duplicate items and do not maintain any particular order. Sets are highly efficient for membership testing, removing duplicates, and performing mathematical operations like union, intersection, and difference.
This tutorial will cover the fundamentals of Python sets, including creation, adding and removing elements, set operations, built-in methods, and practical examples.
A set is an unordered collection of unique elements enclosed in curly braces {} or created using the set() function. Sets do not allow duplicates and are mutable, meaning you can add or remove elements after creation.
Example:
fruits = {"Apple", "Banana", "Cherry"}
numbers = {1, 2, 3, 4}
mixed_set = {1, "Apple", 3.5, True}
In these examples:
fruits contains strings.
numbers contains integers.
mixed_set contains different data types.
Duplicates, if added, are automatically removed.
You can create sets in multiple ways:
Using Curly Braces {}:
fruits = {"Apple", "Banana", "Cherry"}
Using the set() Function:
numbers = set([1, 2, 3, 4, 5])
Empty Set:
empty_set = set()
⚠ Note: Using {} creates an empty dictionary, not a set. To create an empty set, always use set().
Sets are unordered, so you cannot access elements by index. However, you can iterate through a set:
fruits = {"Apple", "Banana", "Cherry"}
for fruit in fruits:
print(fruit)
Because sets are unordered, the order of items may not match the order in which they were added.
You can add elements to a set using the add() or update() methods:
Adding a Single Element:
fruits.add("Mango")
Adding Multiple Elements:
fruits.update(["Pineapple", "Grapes"])
You can remove elements using several methods:
remove() – removes a specific element. Raises an error if the element does not exist:
fruits.remove("Banana")
discard() – removes a specific element. Does not raise an error if the element does not exist:
fruits.discard("Orange") # No error
pop() – removes and returns an arbitrary element:
removed_item = fruits.pop()
clear() – removes all elements:
fruits.clear()
Python sets support mathematical operations, making them very useful for data analysis and problem-solving.
Union – combines elements from two sets (duplicates removed):
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
# Output: {1, 2, 3, 4, 5}
Intersection – returns elements common to both sets:
common = set1.intersection(set2)
# Output: {3}
Difference – returns elements in the first set but not in the second:
diff = set1.difference(set2)
# Output: {1, 2}
Symmetric Difference – returns elements in either set but not in both:
sym_diff = set1.symmetric_difference(set2)
# Output: {1, 2, 4, 5}
Sets are highly efficient for checking whether an element exists:
fruits = {"Apple", "Banana", "Cherry"}
print("Apple" in fruits) # Output: True
print("Mango" not in fruits) # Output: True
Some useful built-in set methods include:
copy() – returns a shallow copy of the set:
copy_set = fruits.copy()
isdisjoint() – checks if two sets have no elements in common:
set1 = {1, 2}
set2 = {3, 4}
print(set1.isdisjoint(set2)) # Output: True
issubset() – checks if a set is a subset of another:
set1 = {1, 2}
set2 = {1, 2, 3, 4}
print(set1.issubset(set2)) # Output: True
issuperset() – checks if a set contains all elements of another set:
print(set2.issuperset(set1)) # Output: True
Python also provides an immutable set called frozenset. You cannot add or remove elements from a frozenset. This is useful when you need a set that should not change:
immutable_set = frozenset([1, 2, 3])
Remove Duplicates from a List:
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
Finding Common Elements Between Two Lists:
list1 = [1, 2, 3]
list2 = [2, 3, 4]
common = set(list1).intersection(list2)
print(common) # Output: {2, 3}
Finding Unique Elements Across Lists:
all_elements = set(list1).union(list2)
Checking Membership Efficiently:
fruits = {"Apple", "Banana", "Cherry"}
if "Apple" in fruits:
print("Apple is in the set")
Set Difference Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
diff = set1.difference(set2)
print(diff) # Output: {1, 2}
Python sets are unordered, mutable, and unique collections of elements. They are particularly useful for eliminating duplicates, performing membership tests, and executing mathematical operations like union, intersection, and difference. Sets are a fundamental part of Python, and mastering them will make your programs more efficient and concise, especially when dealing with collections of data where uniqueness matters. Understanding sets also lays the groundwork for advanced topics like data analysis and algorithm design.
Create a set fruits containing "Apple", "Banana", and "Cherry" and print it.
Add "Mango" to the set fruits.
Add multiple elements "Pineapple" and "Grapes" to the set fruits.
Remove "Banana" from the set fruits using remove() and then try discard() with a non-existent element.
Create two sets set1 = {1, 2, 3} and set2 = {3, 4, 5} and find their union.
Find the intersection of set1 and set2.
Find the difference between set1 and set2 and then between set2 and set1.
Find the symmetric difference of set1 and set2.
Check if set1 is a subset of set2 and if set2 is a superset of set1.
Convert a list with duplicate numbers [1, 2, 2, 3, 4, 4, 5] into a set to remove duplicates.