Create empty Set

 

What You'll Learn: In this tutorial, you'll discover how to create an empty set in Python. Sets are a type of collection that can store unique items.

Using the set() Built-in Function

To create an empty set, you call the set() function without passing any arguments. This function returns an empty set.

Example Code:

python
# Create an empty Set
mySet = set()
# Print the Set
print(mySet)

Output: set()

What's Happening Here?

  • mySet = set() creates an empty set and assigns it to the variable mySet.

Adding Elements to the Set

Once you've created an empty set, you can add items to it using the add() method.

Example Code:

python
# Create an empty set
mySet = set()
# Add elements to set
mySet.add('apple')
mySet.add('banana')
print(mySet)

Output:  {'apple', 'banana'}
 

What's Happening Here?

  • mySet.add('apple') adds 'apple' to the set.
  • mySet.add('banana') adds 'banana' to the set.
  • The set now contains both items.

Try It Yourself: Fun Exercises

  1. Create Your Own Set:
    • Use the set() function to create an empty set.
    • Add your favorite colors to the set using the add() method.
  2. Manage Your Book Collection:
    • Create an empty set for books you've read.
    • Add book titles to the set as you finish reading them.

Summary:

In this Python tutorial, we learned how to create an empty set using the set() function and how to add items to the set using the add() method. Sets are useful for storing unique items and help you manage your data efficiently. Keep experimenting and have fun with sets in Python!