Python – Create a Set
To create a set in Python, enclose the elements in curly braces and assign it to a variable. Or you can pass an iterable (list, tuple, etc.) to the set() built-in function to create a set from the elements of the iterable.
Create set using curly braces
In the following program, we create a set of strings using curly braces and assign it to a variable s
.
Program
</>
Copy
s = {'apple', 'fig', 'banana'}
print(s)
Output
{'fig', 'apple', 'banana'}
Create set using set() builtin function
In the following program, we use set() built-in function to create a set of strings and assign it to a variable s
.
Program
</>
Copy
s = set(['apple', 'fig', 'banana'])
print(s)
Output
{'fig', 'apple', 'banana'}
Create an empty set
To create an empty set in Python, pass no argument to set() built-in function.
Program
</>
Copy
s = set()
print(s)
Output
set()
References
Conclusion
In this Python Tutorial, we learned how to create a set, with the help of example programs.