DEV Community

Cover image for Python Sets : A Comprehensive Guide
Shefali
Shefali

Posted on • Originally published at shefali.dev

Python Sets : A Comprehensive Guide

Python is a really flexible and easy-to-learn language that’s become super popular because it's simple, easy to understand, and can do a whole bunch of different things.

Python offers a rich set of data structures to facilitate efficient manipulation and storage of data. Sets are one of its built-in data structures. In this blog, you will learn about Python sets and their methods.

Let’s jump right into it!🚀

What are Sets?🤔

A set is an unordered collection of data items and is used to store multiple items in a single variable.

In a set, items are separated by commas and enclosed within curly brackets {}.

Sets are unordered which means the sequence in which the items will appear cannot be guaranteed.

Sets are immutable which means you cannot change items of the set once created, but you can remove items and add new items.

Sets do not contain duplicate items.

Example:

data = {"Nina", 36, "Johan", True, 3.9, 36}
print(data)
Enter fullscreen mode Exit fullscreen mode

Output:

{True, 3.9, 36, 'Nina', 'Johan'}
Enter fullscreen mode Exit fullscreen mode

Here you can see that the items of the set occur in random order, so they cannot be accessed using index numbers.

Also in the set, the value 36 was two times but in the output it appeared only one time which means sets do not allow duplicate values.

How to Create an Empty Set?🤔

Let's try to create an empty set by leaving the curly brackets empty.

data = {}
print(type(data))
Enter fullscreen mode Exit fullscreen mode

Now, let's see the output of the above code.

<class 'dict'>
Enter fullscreen mode Exit fullscreen mode

🫨 It's a dictionary, not a set. Then how do I create an empty set?😟

Okay, so for creating an empty set simply just use set() as follows:

data = set()
print(type(data))
Enter fullscreen mode Exit fullscreen mode

Let's see the output of the above code.

<class 'set'>
Enter fullscreen mode Exit fullscreen mode

So for creating an empty set instead of leaving the curly brackets empty, use set().

How to Access Set Items?🤔

Since set items do not have index numbers, so you can access items of set using a loop.

For example:

data = {"Nina", 36, "Johan", True, 3.9, 36}
for item in data:
  print(item)
Enter fullscreen mode Exit fullscreen mode

Output:

True
3.9
Johan
36
Nina
Enter fullscreen mode Exit fullscreen mode

How to check if an item exists in the Set?🤔

You can check the presence of an item in a set using the in keyword.

For example:

data = {"Nina", 36, "Johan", True, 3.9, 36}
if "Johan" in data:
    print("Johan is present.")
else:
    print("Johan is not present.")
Enter fullscreen mode Exit fullscreen mode

Output:

Johan is present.
Enter fullscreen mode Exit fullscreen mode

Python Set union()

The union() method is used to get all the items that are present in two sets. This method returns a new set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 13, 8}
set3 = set1.union(set2)
print(set3)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 3, 6, 8, 12, 13, 56}
Enter fullscreen mode Exit fullscreen mode

Python Set intersection()

The intersection() method is used to get only items that are common in both sets. This method returns a new set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 13, 8}
set3 = set1.intersection(set2)
print(set3)
Enter fullscreen mode Exit fullscreen mode

Output:

{13}
Enter fullscreen mode Exit fullscreen mode

Python Set intersection_update()

The intersection_update() method is similar to the intersection() method but the difference is that intersection_update() method updates into the existing set from another set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 13, 8}
set1.intersection_update(set2)
print(set1)
Enter fullscreen mode Exit fullscreen mode

Output:

{13}
Enter fullscreen mode Exit fullscreen mode

Python Set symmetric_difference()

The symmetric_difference() method is used to get the items that are not common to both sets. This method returns a new set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 13, 8}
set3 = set1.symmetric_difference(set2)
print(set3)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 3, 6, 8, 12, 56}
Enter fullscreen mode Exit fullscreen mode

Python Set symmetric_difference_update()

The symmetric_difference_update() method is similar to the symmetric_difference() method but the difference is that symmetric_difference_update() method updates into the existing set from another set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 13, 8}
set2.symmetric_difference_update(set1)
print(set2)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 3, 6, 8, 12, 56}
Enter fullscreen mode Exit fullscreen mode

Python Set difference()

The difference() method is used to get items that are only present in the original set and not in both sets. This method returns a new set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 13, 8}
set3 = set1.difference(set2)
print(set3)
Enter fullscreen mode Exit fullscreen mode

Output:

{56, 1, 6}
Enter fullscreen mode Exit fullscreen mode

Python Set difference_update()

The difference_update() method is similar to the difference() method but the difference is that difference_update() method updates into the existing set from another set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 13, 8}
set2.difference_update(set1)
print(set2)
Enter fullscreen mode Exit fullscreen mode

Output:

{8, 3, 12}
Enter fullscreen mode Exit fullscreen mode

How to manipulate set items?🤔

You can manipulate set items by using the following built-in methods.

add()

If you want to add a single item to the set, then you can use the add() method.

For example:

set1 = {1, 56, 13, 6}
set1.add(38)
print(set1) #Output: {1, 6, 38, 13, 56}
Enter fullscreen mode Exit fullscreen mode

update()

If you want to add more than one item to the set, then you can create another set or any other iterable object(list, tuple, dictionary), and use the update() method to add it to the existing set.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 38}
set1.update(set2)
print(set1) 
#Output: {1, 3, 6, 38, 56, 12, 13}
Enter fullscreen mode Exit fullscreen mode

remove()/discard()

If you want to remove items from the set, then you can use the remove() and discard() methods.

For example:

set1 = {1, 56, 13, 6}
set1.remove(56)
print(set1) 
#Output: {1, 13, 6}

set2 = {5, 16, 39}
set2.discard(39)
print(set2) 
#Output: {16, 5}
Enter fullscreen mode Exit fullscreen mode

The main difference between these two methods is that, if you try to delete an item that is not present in the set, then remove() method raises an error, whereas discard() method does not raise any error.

Example1:

set1 = {1, 56, 13, 6}
set1.remove(7)
print(set1) 
#Output: KeyError: 7
Enter fullscreen mode Exit fullscreen mode

Example2:

set1 = {1, 56, 13, 6}
set1.discard(7)
print(set1) 
#Output: {56, 1, 13, 6}
Enter fullscreen mode Exit fullscreen mode

del

If you want to delete a set entirely, then you can use del.

del is a keyword, not a method.

For example:

set1 = {1, 56, 13, 6}
del set1
print(set1) #Output: NameError: name 'set1' is not defined
Enter fullscreen mode Exit fullscreen mode

Here you get an error because the entire set has been deleted and there is no variable called set1 anymore.

But what if I want to delete all items of the set, not the entire set? 🤔

Then you have the clear() method.

clear()

If you want to clear all the items of a set, then you can use the clear() method. This gives an empty set.

For example:

set1 = {1, 56, 13, 6}
set1.clear()
print(set1) #Output: set()
Enter fullscreen mode Exit fullscreen mode

pop()

If you want to remove the last item of a set, then you can use the pop() method.

Note: In this method, you can't determine which item gets popped as the sets are unordered.

For example:

set1 = {1, 56, 13, 6}
set1.pop()
print(set1) #Output: {1, 13, 6}
Enter fullscreen mode Exit fullscreen mode

But I want to know which item has been popped out.☹️

Okay, to get the popped item just simply assign it to a variable.

For example:

set1 = {1, 56, 13, 6}
poppedItem = set1.pop()
print(poppedItem) #Output: 56
print(set1) #Output: {1, 13, 6}
Enter fullscreen mode Exit fullscreen mode

isdisjoint()

If you want to check whether the items of a given set are present in another set or not, then you can use the isdisjoint() method.

This method returns False if items are present, else it returns True.

For example:

set1 = {1, 56, 13, 6}
set2 = {3, 12, 38, 13}
print(set1.isdisjoint(set2)) #Output: False
Enter fullscreen mode Exit fullscreen mode

Here, 13 of set2 is present in set1, so it returns False.

issuperset()

If you want to check if all the items of a particular set are present in the original set, then you can use the issuperset() method.

This method returns True if all the items are present, else it returns False.

Example:1

set1 = {1, 56, 13, 6}
set2 = {3, 12, 38, 13}
print(set1.issuperset(set2)) #Output: False
Enter fullscreen mode Exit fullscreen mode

Here, all the items of set2 are not present in set1, so it returns False.

Example:2

set1 = {1, 56, 13, 6, 38, 12}
set2 = {12, 38, 13}
print(set1.issuperset(set2)) #Output: True
Enter fullscreen mode Exit fullscreen mode

Here, all the items of set2 are present in set1, so it returns True.

issubset()

If you want to check if all the items of the original set are present in the particular set, then you can use the issubset() method.

This method returns True if all the items are present, else it returns False.

Example:1

set1 = {1, 56, 13, 6}
set2 = {3, 12, 38}
print(set1.issubset(set2)) #Output: False
Enter fullscreen mode Exit fullscreen mode

Here, all the items of set1 are not present in set2, so it returns False.

Example:2

set1 = {13, 3}
set2 = {3, 12, 38, 13}
print(set1.issubset(set2)) #Output: True
Enter fullscreen mode Exit fullscreen mode

Here, all the items of set1 are present in set2, so it returns True.

That's all for today.

I hope it was helpful.

Thanks for reading.

For more content like this click here.

You can also follow me on X(Twitter) for getting daily tips on web development.

Keep Coding!!

Buy Me A Coffee

Top comments (4)

Collapse
 
glntn101 profile image
Luke

Good guide, thanks!

Collapse
 
devshefali profile image
Shefali

I'm glad you liked it!😊

Collapse
 
flowzai profile image
Flowzai

Thank you for your valuable information

Collapse
 
devshefali profile image
Shefali

Thanks for your feedback!😊