![]() |
VOOZH | about |
Python sets are efficient way to store unique, unordered items. They provide various methods to add elements ensuring no duplicates are present. This article explains how to add items to a set in Python using different methods:
The add() method allows you to add a single item to a set. If the item already exists, the set remains unchanged since sets do not allow duplicate elements.
{1, 2, 3, 4}
In this example, the number 4 is added to the s set. If 4 were already present, the set would remain {1, 2, 3}.
Let's explore other methods of adding elements to a set:
You can also use the update() method to add elements from another set.
{1, 2, 3, 4, 5}
In this example, the elements from set2 are added to set1. Since 3 is already in set1, it is not added again, ensuring all elements remain unique.
You can use the |= operator to perform a union operation, which adds items from another set or iterable to the set.
{1, 2, 3, 4, 5, 6}
This operation is equivalent to using the update() method.
The union() method returns a new set with items from the original set and another iterable. Note that this does not modify the original set unless explicitly assigned back.
{1, 2, 3, 4, 5, 6}