In this tutorial, you’ll learn how to work with sets in Python, specifically how to add elements to an empty set.
Python sets provide a powerful way to store and manipulate unordered collections of unique elements.
They are useful when you want to keep track of unique items, perform set operations such as union and intersection, or efficiently eliminate duplicates from a list.
Starting from Python 2.6, the set data structure is available in the core language (as opposed to using the sets module in older versions).
Creating an empty set
To create an empty set, you can use the built-in function set(). Note that you cannot use the curly brackets {} to create an empty set, as this will create an empty dictionary instead.
For example, to create an empty set called my_set
:
1 |
my_set = set() |
Adding elements to a set
You can add elements to a set using the add() method. This method takes an argument (the item to add) and adds it to the set if it is not already present. If the item is already in the set, the method does nothing.
For example, let’s say you want to create a set of numbers and add the numbers 1, 2, and 3 to it:
1 2 3 4 5 |
my_set = set() my_set.add(1) my_set.add(2) my_set.add(3) |
Now my_set
contains the numbers 1, 2, and 3:
1 |
print(my_set) |
{1, 2, 3}
Adding multiple elements at once
If you want to add multiple elements to a set at once, you can use the update() method. This method takes an iterable (e.g., a list, tuple, or another set) as an argument and adds all of its elements to the set. The following example demonstrates how to add the elements from a list and a tuple:
1 2 3 4 5 6 7 |
my_set = set() numbers_list = [1, 2, 3, 4] numbers_tuple = (5, 6, 7, 8) my_set.update(numbers_list) my_set.update(numbers_tuple) |
Now my_set
contains the numbers 1 through 8:
1 |
print(my_set) |
{1, 2, 3, 4, 5, 6, 7, 8}
Keep in mind that sets only store unique elements, so if your iterable contains any duplicates, they will automatically be eliminated when added to the set.
Full code
Here is the full code that demonstrates adding elements to an empty set and adding multiple elements at once:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
my_set = set() my_set.add(1) my_set.add(2) my_set.add(3) print(my_set) my_set = set() numbers_list = [1, 2, 3, 4] numbers_tuple = (5, 6, 7, 8) my_set.update(numbers_list) my_set.update(numbers_tuple) print(my_set) |
The output of the code above is:
{1, 2, 3} {1, 2, 3, 4, 5, 6, 7, 8}
Conclusion
In this tutorial, you’ve learned how to create an empty set in Python, add elements to it using the add()
and update()
methods, and add multiple elements at once using an iterable. With this knowledge, you can now work with sets more effectively and efficiently in your Python applications.