How To Implement Set In Python

In this tutorial, we will learn how to implement a Set in Python. A Set is an unordered collection of items that is not indexed and does not accept duplicate values. It is mutable, and its elements can be altered after the Set has been created.

Sets are useful for membership testing, removing duplicates from a sequence, and performing mathematical set operations like union, intersection, difference, and symmetric difference.

Step 1: Create a Set

Creating a Set is easy and can be done in two ways: using curly braces or the set() function. Below are examples of both approaches:


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

Observe how the duplicate value 2 was automatically removed from set_2.

Step 2: Add and Remove Items

Since a Set is mutable, you can add and remove items using the add() and remove() functions, respectively.


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

The discard() function can also remove an item from a Set, but unlike remove(), it does not raise an error if the item is not found in the Set:


{1, 2, 5, 6} 

Step 3: Iterate Over a Set

Although a Set is unordered and not indexed, you can still iterate over its elements using a simple for loop:



Step 4: Set Operations

Python Sets support various mathematical set operations, such as union, intersection, difference, and symmetric difference. Here is an example for each, using two Sets:


Union : {1, 2, 3, 4, 5, 6, 7, 8}
Intersection : {4, 5}
Difference : {1, 2, 3}
Symmetric difference : {1, 2, 3, 6, 7, 8} 

Alternatively, you can use the corresponding set methods to achieve the same results:

Full Code


In this tutorial, you have learned how to implement a Set in Python, add and remove items, iterate over a Set, and perform various mathematical set operations. With Sets, you can efficiently perform a wide range of tasks, such as membership testing and computing the union or intersection of two collections.