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 Python Sets?🤔

Python sets are an unordered collection of data items and are used to store multiple items in a single variable.

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

Python 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)

Output:

{True, 3.9, 36, 'Nina', 'Johan'}

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 once, which means sets do not allow duplicate values.


How to Create Empty Python Sets?🤔

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

data = {}
print(type(data))

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

<class 'dict'>

🫨 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))

Let’s see the output of the above code.

<class 'set'>

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


How to Access Items of Python Sets?🤔

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)

Output:

True
3.9
Johan
36
Nina

How to check if an item exists in the Python 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.")

Output:

Johan is present.

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)

Output:

{1, 3, 6, 8, 12, 13, 56}

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)

Output:

{13}

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)

Output:

{13}

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)

Output:

{1, 3, 6, 8, 12, 56}

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)

Output:

{1, 3, 6, 8, 12, 56}

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)

Output:

{56, 1, 6}

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)

Output:

{8, 3, 12}

How to manipulate items of Python sets?🤔

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}

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}

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}

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

Example2:

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

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

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()

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}

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}

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

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

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

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

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

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


That’s all for today!

If you’re new to web development, check out Learnify — my curated platform with beginner-friendly tutorials to help you learn web development step-by-step with examples and simple explanations.

If you enjoy my work and want to support what I do:

👉 Become a Patreon supporter
👉 Or buy me a coffee

Every small gesture keeps me going! 💛

Follow me on X (Twitter) to get daily web development tips & insights.


Enjoyed reading? You may also find these articles helpful.

Mastering Tuples in Python: A Comprehensive Guide

Everything You Need to Know About Python Lists

19 thoughts on “Python Sets : A Comprehensive Guide”

  1. It is appropriate time to make some plans for the future and it is time to be happy. I have read this post and if I could I want to suggest you few interesting things or suggestions. Perhaps you can write next articles referring to this article. I wish to read even more things about it!

    Reply
  2. I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to design my own blog and would like to find out where u got this from. cheers

    Reply
  3. Aw, this was an incredibly good post. Taking the time and actual
    effort to produce a very good article… but what can I say… I procrastinate
    a lot and don’t manage to get anything done.

    Reply
  4. Hello I am so excited I found your webpage, I really found you by mistake, while
    I was researching on Aol for something else, Regardless I am here now and would
    just like to say thanks a lot for a incredible post and a all
    round interesting blog (I also love the theme/design),
    I don’t have time to browse it all at the moment but I have
    book-marked it and also added your RSS feeds, so when I have time I
    will be back to read a great deal more, Please do keep up the excellent work.

    Reply
  5. Everything is very open with a precise explanation of
    the challenges. It was really informative.
    Your site is very helpful. Many thanks for sharing!

    Reply
  6. Generally I do not read post on blogs, however I wish to
    say that this write-up very pressured me to check out and do it!
    Your writing taste has been surprised me. Thanks,
    quite great article.

    Reply

Leave a Comment