Home » Python Basics » Python sets

# Python sets Python sets (a built-in type) provides a lot of functionality which are same as the Set theory in Mathematics. However, interpretation and symbol may be little varied concerning standard symbol used in Mathematics. We do not need to import set library to use in Python program instead, it is loaded by default. In this single tutorial, you will learn everything about Python sets.

## Introduction

SETs are an unordered collection of unique elements group together under one name. Set can hold elements of multiple data types (Heterogenous). A set will always have unique elements (no duplication allowed), unlike List and Tuples in Python. A set object is also a collection of distinct hashable objects. An object is hashable if it has a hash value which never changes during its lifetime. Hashability makes an object usable as a dictionary key and a set member because these data structures use the hash value internally.

Common uses of Python sets include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. Image shown below contains two different sets (Alphabet and Numbers) each having a unique and immutable object.

## Creating Python sets

Python sets can be created in two ways

1. Using curly braces { }
2. Using inbuilt set( ) function

Note: Avoid using Python’s reserve keyword and any built-in class name, as a set variable name. It’s not the best practice for Python programming.

A set is created by placing all the items (elements) inside curly braces { }, as shown in the example below.

``````s1 = { }  # This will create an empty set
s2 = { 1, 'aipython', 20.67 }``````

Another way to create (or define) Python set is by using a set( ) function. Look at the example shown below

``````s3 = set( ) # This will create an empty set
s4 = set({ 1, 'aipython', 20.67})``````

You would have noticed that the first method (using curly braces { }) is more convenient than the other one. You can choose any of the two methods to create a set in Python.

There is no limitation on putting the number of elements but there is always a restriction to place mutable type elements such as List and Dictionary inside a set. If we try to place a list (with some elements) in a set, it will throw an error, as shown below.

``````s5 = { 1, 2, 3, [5, 6, 7, 8] }
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'``````

## Add elements to Python sets

Python sets support the addition of elements in two ways, One element at a time using add ( ) method and more than one elements using update ( ) method. Both these methods are described below,

### Adding one element to set in Python

One element can be added with the help of add ( ) method in Python sets. Python code for the same is shown below,

``````set1 = {1, 3, 4}
print(set1)
{1, 2, 3, 4}``````

### Adding multiple elements to set in Python

More than one (multiple) elements can be added with the help of update( ) method in Python sets. Python code for the same is shown below,

``````set2 = {1, 2, 3}
set2.update ([4, 5, 6])
Output -> {1, 2, 3, 4, 5, 6}``````

## Removing elements from Python sets

One or multiple elements can be removed from a set using the following methods. They differ in the way it returns the output.

i) remove ( )

iii) pop ( )

### Remove ( )

Remove ( ) methods are useful when you want to remove a particular element (one at a time) from the set and it will throw an error if the element is not found (not present) in the original set.

Code below shows the remove ( ) method in action.

``````set1 = {1, 2, 3, 4, “a”, “p”}
set1.remove (2)
print (set1)
{1, 3, 4, “a”, “p”}

set1.remove (5)

Discard ( ) methods are useful as it will remove a particular element (one at a time) and does not throws an error if the element is not found (or not present) in the original set.

Code below shows the discard ( ) method in action.

``````set1 = {1, 3, 4, “a”, “p”}
print (set1)
{1, 3, 4 “p”}

print (set1)
{1, 3, 4, “p”}``````

### Pop ( )

Pop ( ) methods are useful as it will remove any element (one at a time) in random order. Set is an unordered collection, therefore, pop () does not require any arguments (in this case any index). You can also consider pop () as an uncontrolled method to remove a single element from Sets in Python. Code below shows the pop ( ) method in action.

``````set1 = {1, 3, 4, “p”}
set1.pop (  )
3  # any random element will be removed (your result could be different)``````

## Methods associated with Python sets

There are several built-in methods associated with a set in Python. As you know, you can check all the methods associated with an object in Python using dir ( ) command. Python dir (object), displays the most relevant attributes of that particular object. The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information.

Let’s look at the dir ( ) function in Python set’s context.

``````set1 = { 1, 2, 3, 4}

dir (set1)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']``````

### Commonly used function with Python Sets

Out of all the methods that you have seen using dir ( ) method, there are only a few methods (function) which are used commonly. You have already used some of them, such as add, update, remove, pop, & discard.

Let’s look at the following commonly used function in Python Sets.

#### Membership Function

This checks for the presence of a particular element in the set.

``````num_set = {1 ,3, 5, 7, 9, 10}
7 in num_set
True

2 in num_set
False

1 not in num_set
False``````

#### Miscellaneous functions

``````len (num_set) # Returns the number of elements in a set
6``````
``````# copy () - Make a new copy of existing set and store it in another set
new_set = num_set.copy()``````
``````# clear() - method empties the set (delete all the elements in one go
num_set.clear()``````
``````# del - This Keyword delete the set completely.
del num_set``````

Later in this tutorial, you will see some more of them such as union, issubset, issuperset, difference_update and many others.

## Python sets operations

In this section, you will learn about various set operations that are common to set theory in general. We have included a video animation with each operation for better understanding.

### Union of sets

Once performed on two sets, creates a new set which contains elements from both the set (but no duplication of an element occur). Union operation, in Python, can be achieved by two methods. First, using “|” symbol and second, using union ( ) method.

Let see them in action.

``````A = {1, 2, 3} and B = {2, 3, 4, 5}
C = A | B # using symbol method
C = A . union( B ) # using union method
Output -> {1, 2, 3, 4, 5}``````

### Intersection of sets

Once performed on two sets, creates a new set which contains elements common to both the set (but no duplication of elements occur). Intersection operation, in Python, can be achieved by two methods. First, using “&” symbol and second, using the intersection ( ) method.

Let see them in action

``````A = {1, 2, 3, 4} and B = {3,4,5,6}
C = A & B  # using symbol method
C = A . intersection( B ) # using the intersection method
Output -> { 3,4 }``````

### Difference of sets

Once performed on two sets, creates a new set which contains elements present in one set (set “A” is taken as reference) but not in other sets. Difference operation, in Python, can be achieved by two methods. First, using “” symbol and second, using the difference ( ) method.

Let see them in action

``````A = {1, 2, 3, 4} and B = {3,4,5,6}
C = A - B # using symbol method
C = A . difference ( B ) # using the difference method
Output -> { 1,2 }``````

### Symmetric difference of sets

Once performed on two sets, creates a new set which contains elements besides the common elements from both the sets. Symmetric difference operation, in Python, can be achieved by two methods. First, using “^” symbol and second, using the symmetric_difference ( ) method.

Let see them in action

``````C = A ^ B # using symbol method
C = A . symmetric_difference ( B ) # using the symmetric_difference method
Output -> { 1,2 ,5,6 }``````

## Subset and Superset in Python

Subset: SetB is said to be a subset of setA if all the elements of SetB are present in setA. Test for Subset, in Python, can be achieved by two methods. First, using “<=” symbol and second, using the issubset( ) method. Subset method does not returns any new set rather it will return True or False. Let see them in action

``````A = {1, 2, 3, 4, 5} and B = {2,3,4}
B <= A  # using symbol method
B . issubset (A ) # using issubset method
Output -> True``````

Superset: SetA is said to be superset of setB if all the elements of SetB are present in setA. Test for Superset, in Python, can be achieved by two methods. First, using “>=” symbol and second, using the issuperset( ) method. Superset method does not returns any new set rather it will return True or False. Let see them in action

``````A = {1, 2, 3, 4, 5} and B = {2,3,4}
A >= B # using symbol method
A . issuperset (B ) # using issuperset method
Output -> True``````

## Quick application (Reading bonus) 💸

If you are reading until this point, then you deserve some reading rewards and here it is. This is a very common and most frequently asked question. Many Python beginners struggle to get this solved in the first go.

How to remove duplicate elements from a List?

<<< Pause for a moment and think about the solution >>>

Answer: Just pass the list to the python set () and all duplicates will be removed and in case you want it to be used as a list then again pass that set in list () function. See the code below,

``````List1 = [ 1, 2, 3, 5, 3, 2, 4, 7 ]
List_without_duplicate = set (List1)
Output -> (1, 2, 3, 5, 4, 7) # converted to set

back_to_list = list (List_without_duplicate)
Output -> [1, 2, 3, 5, 4, 7] # again converted to list``````

## Conclusion

After reading this tutorial, you have learned about Sets in Python and a general idea about set theory in practice. You have also learned to create a set, modify (or add ) elements and delete element from the set. You have also seen to use dir () methods and various common methods associated with the set in Python. Further, you have seen the common set operation such as Union, Intersection, Difference, Symmetric difference, Subset and Superset. I hope you have learnt something new or at least had a thorough revision of the topic.

Don’t stop here, try practising more on this topic because that is one and only way to retain the knowledge.

Keep Learning and Keep Growing !!

### 1 thought on “Python sets”

1. Excellent Tutorials.Meticulous, Simple and practical.

Scroll to Top