3 Easy Ways to Initialize a Set in Python

0
48
3 Easy Ways to Initialize a Set in Python

Python Set is an unordered collection with no duplicate elements. There are many ways to initialize a list, and in this tutorial, we will see three different ways to create a list.

How to initialize a set in Python

Three easy ways to initialize a set in Python.

  1. Using set() constructor: It returns a new set with initialized elements.
  2. Use set literal: It creates a set with provided elements.
  3. Using the unpacking operator: It will help you create a set from a list.

Using Set constructor

The set() constructor returns a new set initialized with elements of the specified iterable. The set() constructor accepts a list of elements as parameters and returns a new set that contains only those elements.

Program

set_a = set(("Playstation", "Xbox Series X", "Xbox Series S"))
print(set_a)

set_b = set(["Rangnarok", "Halo", "Metal gear solid"])
print(set_b)

Output

{'Playstation', 'Xbox Series S', 'Xbox Series X'}
{'Halo', 'Metal gear solid', 'Rangnarok'}

We passed elements as arguments to the set() constructor, and it returned the newly created set.

How to create an empty set?

To create an empty set, use the set constructor() and do not pass any arguments. It returns an empty set.

set_e = set()
print(set_e)

Output

set()

And the empty set is created.

Using Set literal

Use the set literal { } syntax and put a comma-separated list of items placed within the curly braces { }. Put each element with a comma inside the curly braces.

Program

set_a = {"Playstation", "Xbox Series X", "Xbox Series S"}
print(set_a)

Output

{'Playstation', 'Xbox Series X', 'Xbox Series S'}

We passed comma-separated values to the curly braces, and it returned the new set.

Using the unpacking operator

The single asterisk operator ( * ) unpacks the values from iterable objects in Python. Initialize a list and unpack its elements inside the { } curly braces or set literal.

Program

list_a = ["Playstation", "Xbox Series X", "Xbox Series S"]
set_a = {*list_a}
print(set_a)

Output

{'Xbox Series S', 'Playstation', 'Xbox Series X'}

The unpack operator(*) unpacks all the list elements inside the set literal, and now it becomes a set with initial values.

Conclusion

The best way to initialize a list in Python, use the set() constructor. If you want to create an empty constructor, don’t pass any arguments.

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.