Python Sets with Examples

Spread the love

In this tutorial, you will learn about python sets with examples.

What is Sets In python:

A set object is an unordered collection of distinct hashable objects. We can use this remove duplicates and check membership. It is mutable, we can add or remove items from set.

By using sets, We can able to do mathematical operations like union, intersection, difference, and symmetric difference

How to Create Sets in python:

You can create sets by placing elements in curly braces. You can add interger, float, strings. But it’s not allow mutable elements like in list, set and dictionary as elements.

Note: We need call with  set object with set()functions, Otherwise it will consider as a dictionary in python.

data = {} print(type(data)) data=set(data) print(type(data)) data={1,2,3,4,4,5,6} print(type(data))


<class 'dict'>
<class 'set'>
<class 'set'>

Python Sets Program Examples :

#program on integer and string data:

Numeric_data={1,2,3,4,4,5,6} string_data={'ravi','raju','venkat','ravi'} print(set(Numeric_data)) print(set(string_data))


{1, 2, 3, 4, 5, 6}
{'ravi', 'raju', 'venkat'}

How to change elements in sets:

You can change elements in sets by using add(), update() and remove () functions

#python set program to add, change, remove elements from sets

numeric_data={1,2,3,4,4,5,6} string_data={'ravi','raju','venkat','ravi'} print(set(numeric_data)) print(set(string_data)) print("after Adding data") #adding elements to sets string_data.add('david') print(numeric_data) #updating elements to sets numeric_data.update([7,8]) print("after Update data") print(string_data) #remove elements from sets numeric_data.remove(7) string_data.remove('david') print("after remove data") print(numeric_data) print(string_data)


{1, 2, 3, 4, 5, 6}
{'ravi', 'raju', 'venkat'}
after Adding  data
{1, 2, 3, 4, 5, 6}
after Update data
{'ravi', 'raju', 'venkat', 'david'}
after remove data
{1, 2, 3, 4, 5, 6, 8}
{'ravi', 'raju', 'venkat'}



Leave a Reply

Your email address will not be published. Required fields are marked *