What is Python Set: 3 Examples of How to Use

What is set in Python?

In Python, the Set is almost similar to the dictionary. A Python set is a dictionary with no values.

An example of Set type

As described in the dictionary chapter, the dictionary data type works with the key – value pairs as shown below:

dictionary_name = {key:value, key:value, …..}

Whereas a set works like this:

set_name = {key1, key2, …..}

Practically, the set type is used less in Python. Uses may include removing duplicates from a sequence, testing of membership, a few mathematical operations like the difference, symmetric difference, union etc.

Example of using a set

The example below creates a set with four keys. Two are given the same name. The next statement will print that set.

Python set example

See this example online

The output will be:

{’emp_salary’, ’emp_address’, ’emp_name’}

As you can see, the duplicate keys are printed once.

Getting length of set

In the following example of using the Set Python type, we will get the length of the set by using the len method. See the example:

Python set length

See this example online

The output will be:

{’emp_name’, ’emp_salary’, ’emp_address’}


The length of the set is 3, as the duplicate key is omitted.

Set clear method

You can use the clear method to remove all elements of Set just like in the dictionary. See example below:

Python set clear

See this example online

The output will be:

{’emp_name’, ’emp_address’, ’emp_salary’}
Set after clear set()


Further Reading: Python dictionary | Python Tuple | Arrays in Python