In this tutorial, we will learn about the Set in Python. Its types, and how to use them with the help of examples

Set is use to store the group of unique object (duplicates are not allow). Declare the set data by using curly brasses { }. Set is mutable allows modifications. A Set insertion order is not preserved, indexing is not support. Heterogeneous elements are allow. We can represent set elements within curly braces and with comma separated. We can apply mathematical operations like union, intersection, difference etc on set

Creating a Set

# integer type
roll = {2, 4, 6, 8, 10}
print('Roll numder:', roll)

# string type
letters = {'b', 'a', 's', 'i', 'c'}
print('Letter:', letters)

# mixed data types
key = {'Basic', 12, -12, 'Engineer'}
print('mixed data types:', key)
A Creating a Set

Let’s run the code

Creating a Set in python
Creating a Set in python

Python Set Method

add()It adds an item to the set. It has no effect if the item is already present in the set
clear()It deletes all the items from the set.
copy()It returns a shallow copy of the set.
discard()It removes the specified item from the set.
intersection()It returns a new set that contains only the common elements of both the sets.
intersection_update()It removes the items from the original set that are not present in both the sets 
Isdisjoint()Return True if two sets have a null intersection.
Issubset()Report whether another set contains this set.
Issuperset()Report whether this set contains another set.
pop()Remove and return an arbitrary set element that is the last element of the set. Raises KeyError if the set is empty.
remove()Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.
union()Return the union of sets as a new set.
update()Update a set with the union of itself and others.
set method

Example of set method in Python

# add 
basic = {'b', 's', 'i','c'}
print("Letters are:",basic)
def Remove(key):
    print (key)
key = set([1, 2, 3, 1, 4, 1])
a = {1, 2, 3}
a1 = {1, 2, 3, 4} 
a2 = a1.copy()
A = {2, 4, 6, 8}
B = {4, 8, 12, 16} 
print("A U B:", A.union(B))
x1 = {2, 4, 6,8}
x2 = {2, 8, 9}
A Example of set method in Python

Let’s run the code

Example of set method in Python
Example of set method in Python

If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.

To know more about Python Wikipedia please click here .

Stay Connected Stay Safe, Thank you

Categories: Software

Basic Engineer

Hey Readers! We have more than fifteen years of experience in Software Development, IoT, Telecom, Banking, Finance and Embedded domain. Currently we are actively working on Data Science, ML and AI with multiple market leaders worldwide. Happy Reading. Cheers!


Leave a Reply

Avatar placeholder

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