How To Make A Set In Python

In this tutorial, we will learn how to make a set in Python. A set is an unordered and unindexed collection of unique elements, which means that it cannot contain duplicate elements.

Using sets can make certain types of operations such as intersection or union more efficient than using lists or arrays. Let’s dive into how to create a set in Python using various methods.

Step 1: Creating a Set Using Curly Braces

One way to create a set is by using curly braces and comma-separated elements. Place the unique elements inside the braces to create a set.

{1, 2, 3, 4}

Note: If you try to include duplicate elements, Python will automatically remove them and only store the unique elements.

Step 2: Creating a Set Using the Set Constructor

Another way to create a set is by using the set() constructor. You can pass a list, tuple, or other iterable types, such as strings, as an argument to the set() constructor.

{1, 2, 3, 4}

As you can see, the duplicate value 4 from the list has been removed.

Step 3: Adding and Removing Elements from a Set

To add an element to the set, use the add() method. To remove an element, use the remove() method or the discard() method. The remove() method raises an error if the specified element is not found in the set, while discard() does not.

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

Step 4: Common Operations on Sets

You can perform common operations such as union, intersection, and difference on sets.

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

Python also supports set operations using special characters like | for union, & for intersection and - for difference.

Here’s the full code:


In this tutorial, we learned how to create a set in Python using curly braces and the set() constructor, as well as how to add and remove elements, and perform common set operations like union, intersection, and difference. Sets are a useful data structure when working with unique elements or sets, and they can provide efficient operations compared to lists or arrays.