How to Create an Empty Set in Python



Python


In this article, we show how to create an empty set in Python.

First of all, what is a set in Python?

A set is a collection of unique items.

So, in a set, no items can be repeated.

So if you want to create a list of items in Python, in which each item is unique, then you would create a set.

To create an empty set in Python, the following code below is used.



So we created a variable, called set1, and set it equal to set(). This creates an empty set in Python.

So why would we need to create an empty set in Python?

What would be the use of this?

You might create an empty set if you eventually want to create a list of unique user input.

Say, for example, you are creating a form that accepts user input and you want each item that the user enters to be unique.

In this case, you can create an empty set, go through all the items that the user has entered, and store them in the set.

Since a set is a collection of unique items, any duplicates are removed.

The code to accept only unique input from a user is shown below.



So if I entered in the following once the program is run, I get the following output.



So you can see the use of sets and why you would create an empty set in Python.

There are many other reasons to use sets.

For example, if you're creating a web crawler, you don't want to index the same URL over and over and over. You would just want to index a given URL once. Therefore, you would create an empty set and store URLs in this set. That way, you won't duplicate the same URLs.

So there are many reasons for creating empty sets in Python, all for not duplicating given values.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...