How to Create a Set in Python
To create a set in Python, you can use the set() function or {} curly braces.
The following examples show how to create a set using two different methods in Python.
Using set() Function
We can use the set() function to create a set.
Let’s see how to use the set() function in Python:
# Create empty set
set_ = set()
# Add elements to set
set_.add(1)
set_.add(2)
set_.add(3)
# Show set
print(set_)
Output: 👇️
{1, 2, 3}
In this example, we use the set() function to create an empty set set_ and then add elements to it using the add() function. The output shows the set created using the set() function.
Using {} Curly Braces
We can use {} curly braces to create a set in Python.
Let’s see how to use {} curly braces in Python:
# Create set
set_ = {"a", "b", "c", "d"}
# Show set
print(set_)
Output: 👇️
{'a', 'd', 'c', 'b'}
In this example, we use {} curly braces to create a set set_. The output shows the set created using {} curly braces.
Conclusion
We can use the set() function or {} curly braces to create a set in Python.