Python Program to Perform Operations on Set

Computer Bits Daily
2 min readJun 30, 2023

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)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Computer Bits Daily
Computer Bits Daily

Written by Computer Bits Daily

Learning Computer skills and Computer technology by learning and sharing

No responses yet

Write a response