Initialize a Python set
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = set((1, 2, 3)) # create set from tuple print(s) # { 1, 2, 3} s = set([1, 2, 3]) # create set from list print(s) # { 1, 2, 3} s = set('ABC') # create set from string print(s) # {'C', 'B', 'A'} |
If no argument is passed to the set constructor, an empty set is created.
|
1 2 3 4 5 |
if __name__ == '__main__': s = set() print(s) # set() |
2. Using Set literal syntax
You can also create a set with a comma-separated list of items placed within the curly braces {}.
|
1 2 3 4 5 |
if __name__ == '__main__': s = {1, 2, 3} print(s) # {1, 2, 3} |
Note that if no items are passed, an empty dictionary is created instead. To create an empty set, we should use the set constructor.
|
1 2 3 4 5 |
if __name__ == '__main__': s = {} print(type(s)) # <class 'dict'> |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = [1, 2, 3] # list s = {*x} print(s) # { 1, 2, 3} |
That’s all about initializing a set in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)