You are currently viewing Sets and Set Manipulation in Python’s Data Structures

Sets and Set Manipulation in Python’s Data Structures

In Python, a set is an unordered collection of unique elements. It is similar to a list or a tuple, but the elements in a set are not indexed and cannot be accessed by their position. Instead, they are stored in an arbitrary order, and duplicates are automatically removed. The set is represented by curly braces {} or by the set() function.

Creating a Set

We can create a set by enclosing a comma-separated sequence of elements within curly braces {}. We can also use the set() function to create a set.

# Creating a set
set1 = {1, 2, 3, 4, 5}
set2 = set([3, 4, 5, 6, 7])

Adding and Removing Elements

We can add elements to a set using the add() method, and we can remove elements using the remove() or discard() method.

# Adding and removing elements from a set

Set Operations

We can perform various set operations like union, intersection, difference, symmetric difference, etc., using the corresponding methods or operators.

# Set operations
set3 = set1.union(set2)
set4 = set1.intersection(set2)
set5 = set1.difference(set2)
set6 = set1.symmetric_difference(set2)

Iterating Over a Set

We can iterate over a set using a loop.

# Iterating over a set
for element in set1:

Set Membership and Subset Operations

We can check if an element is present in a set using the in the keyword. We can also check if a set is a subset or superset of another set using the corresponding methods or operators.

# Membership and subset operations
if 3 in set1:
    print("3 is present in set1")
if set1.issubset(set3):
    print("set1 is a subset of set3")
if set3.issuperset(set1):
    print("set3 is a superset of set1")


Suppose we have two sets of students, one who has enrolled for a Math course and one who has enrolled in a Computer Science course. We want to find out the students who have enrolled for both courses.

math_students = {"Alice", "Bob", "Charlie", "David", "Emily"}
cs_students = {"Charlie", "David", "Frank", "Emily", "George"}

# Find students who have enrolled for both courses
common_students = math_students.intersection(cs_students)
print(common_students) # Output: {'Charlie', 'David', 'Emily'}

Leave a Reply