- Live Instructor-led Classes
- Expert Education
- 24*7 Support
- Flexible Schedule

Set datatype in Python is mutable, iterable and does not have any duplicate elements. It is an unordered collection of elements which means that a set is a collection that stores elements of different data types. Remember that, set doesn’t index them in a particular order. Let us look at some of the properties of set in python. Sets are usually used to perform some mathematical functions such as union, interest, etc.

- In the set, elements don’t have a specific order.
- Set can’t have duplicates. Each item is unique.
- Set elements are immutable. They can’t accept changes once added.
- But the set is mutable. Set allows addition and deletion operations.

One of the major advantages of using sets in Python is that unlike some other datatypes like lists, set in Python contains a highly optimized method for the sole purpose of checking whether a particular element is included in a set or not.

Also, since sets in Python are mutable, we can add and remove elements from a set, however every element that is added in the set must be unique and immutable, that is, you cannot change elements once they have been added.

In this module, we will learn all about sets in order to get started with it, following is the list of all the topics that we will be covering, in case you need to jump to a specific one.

So, without any further delay, let’s get started.

**Learn Python in 16 hrs from experts**

1. Using comma to separate and curly braces to group elements.

myset = {“apple”, “banana”, “cherry”}

print(myset)

print(myset)

Output:

{‘cherry’, ‘banana’, ‘apple’}

2. Using the inbuilt Set() method with the elements that we want to add as the parameters.

myset = set((“apple”, “banana”, “cherry”)) # note the double round-brackets

print(myset)

print(myset)

Output:

{‘cherry’, ‘banana’, ‘apple’}

Remember that once a set is created you can’t change that you can only add elements. You can remove and then add element but cannot change the existing element. Now let us see how to add items in a python set.

Wish to Learn Python? Click Here

1. Using add() method with the element as parameter in the method:

myset = {“apple”, “banana”, “cherry”}

myset.add(“orange”)

print(myset)

myset.add(“orange”)

print(myset)

Output:

{‘cherry’, ‘orange’, ‘banana’, ‘apple’}

2. Using update()

myset = {“apple”, “banana”, “cherry”}

myset.update([“orange”, “mango”, “grapes”])

print(myset)

myset.update([“orange”, “mango”, “grapes”])

print(myset)

Output:

{‘cherry’, ‘mango’, ‘banana’, ‘apple’, ‘orange’, ‘grapes’}

Remove operation can be performed by using the following methods

1. Using remove() method:

myset = {“apple”, “banana”, “cherry”}

myset.remove(“banana”)

print(myset)

myset.remove(“banana”)

print(myset)

output:

{‘cherry’, ‘apple’}

Note: If the item to be removed does not exist, remove() will raise an error

2. Using discard():

myset = {“apple”, “banana”, “cherry”}

myset.discard(“banana”)

print(myset)

myset.discard(“banana”)

print(myset)

Output:

{‘cherry’, ‘apple’}

Note: If the item to be removed does not exist, discard() will not raise an error.

3. Using pop():

Remember that pop() will remove the last item of the set. Since set is unordered, we should avoid performing pop() in set.

myset = {“apple”, “banana”, “cherry”}

x = myset.pop()

print(x)

print(myset)

x = myset.pop()

print(x)

print(myset)

Output:

{‘banana’, ‘apple’}

To print the length of the set we can simply use the inbuilt len() method as shown below:

myset = {“apple”, “banana”, “cherry”}

print(len(myset))

print(len(myset))

Output:

3

To clear a set completely we can use either clear() method or del() method.

1. Using clear()

myset = {“apple”, “banana”, “cherry”}

myset.clear()

print(myset)

myset.clear()

print(myset)

2. Using del():

myset = {“apple”, “banana”, “cherry”}

del myset

print(myset)

del myset

print(myset)

Output:

Traceback (most recent call last):

File “”, line 1, in

NameError: name ‘myset’ is not defined

File “”, line 1, in

NameError: name ‘myset’ is not defined

As discussed above, Sets in Python are used to carry out mathematical set operations such as union, intersection, etc. Let’s see a few examples of these mathematical operations.

To perform union, we use “|” operator. We can also use an inbuilt method called union(), which will give the same result.

The result of the union of two sets, say set A and set B, is a set containing the elements of both the sets.

The following code block shows the union of set A and set B using Sets in Python.

Set_A = {1,2,3,4,5}

Set_B = {4,5,6,7}

print(Set_A | Set_B)

Set_B = {4,5,6,7}

print(Set_A | Set_B)

Output:

{1, 2, 3, 4, 5, 6}

Become Python Certified in 16 hrs.

CLICK HERE

To perform intersection, we use & operator. We can also use the inbuilt method named as intersection() to get the same result.

The intersection of two sets, say Set A and Set B can results in a set that contains the elements that are common in both the sets, that is the overlapping part in the diagram below.

The following code block shows the union of set A and set B using Sets in Python.

Set_A = {1,2,3,4,5}

Set_B = {4,5,6,7}

print (Set_A & Set_B)

Set_B = {4,5,6,7}

print (Set_A & Set_B)

Output:

{4, 5}

Method | Description |

update() | It updates the set with the union of this set and others |

add() | It adds an element to the set |

clear() | It removes all the elements from the set |

copy() | It returns a copy of the set |

difference() | It returns a set containing the difference between two or more sets |

difference_update() | It removes the items in this set that are also included in another, specified set |

discard() | It removes the specified item |

remove() | It removes the specified element |

pop() | It removes an element from the set |

intersection() | It returns a set, that is the intersection of two other sets |

intersection_update() | It removes the items in this set that are not present in other, specified set(s) |

isdisjoint() | It returns whether two sets have a intersection or not |

issubset() | It returns whether another set contains this set or not |

issuperset() | It returns whether this set contains another set or not |

symmetric_difference() | It returns a set with the symmetric differences of two sets |

symmetric_difference() | It returns a set with the symmetric differences of two sets |

union() or | | It returns a set containing the union of sets |

intersection or & | It returns a set comprising common elements in both the sets |

Now that we are familiar with the set and its operations, we will be discussing another very important datatype which is nothing but a dictionary in the next module. See you there!

Further, check our Python course for certification and prepare yourself with our free Python interview questions listed by the experts.

Previous NextDownload Interview Questions asked by top MNCs in 2019?

- To avail this offer, enroll before 26th May 2019.
- This offer cannot be combined with any other offer.
- This offer is valid on selected courses only.
- Cashback will be accumulated in Intellipaat e-wallet
- Please use coupon codes mentioned below to avail the offer

## "0 Responses on Python Sets"