This post will discuss how to initialize a set in Python.

A set is a data structure used to store distinct values and offers fast insertion & retrieval times. There are several ways to initialize a set in Python, as discussed below:

1. Using Set constructor

The set constructor set() returns a new set initialized with elements of the specified iterable. Note that if an element is repeated in the iterable, the resultant set silently discards the duplicate.

Download  Run Code

 
If no argument is passed to the set constructor, an empty set is created.

Download  Run Code

2. Using Set literal syntax

You can also create a set with a comma-separated list of items placed within the curly braces {}.

Download  Run Code

 
Note that if no items are passed, an empty dictionary is created instead. To create an empty set, we should use the set constructor.

Download  Run Code

3. Using Iterable Unpacking Operator

To create a set from a list, you can unpack items from the list inside {} syntax. This can be done using the *-operator.

Download  Run Code

That’s all about initializing a set in Python.