Python Program to Perform Operations on Set
Python provides a powerful data structure called a set that allows you to store a collection of unique elements. Sets are unordered and mutable, making them efficient for membership testing and performing various set operations. In this blog post, we will explore a Python program that demonstrates several operations on sets. We will cover creating two different sets, printing set items, adding and removing items from a set, performing operations like union, intersection, difference, and symmetric difference, and checking if a set is a subset of another set. By the end of this guide, you will have a solid understanding of working with sets in Python. Let’s dive in!

Table of Contents
- Creating Two Different Sets with Data
- Printing Set Items
- Adding/Removing Items in/from a Set
- Performing Operations on Sets
| Learn Python with “ Computer Courses — All in One “
Creating Two Different Sets with Data
To create two different sets with data, we can use the set() function. Here’s an example:
set1 = set([1, 2, 3, 4, 5])
set2 = set([4, 5, 6, 7, 8])
In this example, we have created two sets called set1 and set2 with different data.
Printing Set Items
To print the items in a set, we can use a for loop to iterate over the set and print each item. Here’s an example:
set1 = set([1, 2, 3, 4, 5])
for item in set1:
print(item)
This will output:
1
2
3
4
5
Adding/Removing Items in/from a Set
To add an item to a set, we can use the add() function. Here’s an example:
set1 = set([1, 2, 3, 4, 5])
set1.add(6)
print(set1)