Open In App

Python - Add Set Items

Last Updated : 06 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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:

Add single set item using add() Method

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.

Python
s = {1, 2, 3}
s.add(4)
print(s)  

Output
{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:

Adding Elements from Another Set

You can also use the update() method to add elements from another set.

Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1)  

Output
{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.

Using |= Operator

You can use the |= operator to perform a union operation, which adds items from another set or iterable to the set.

Python
s = {1, 2, 3}
s |= {4, 5, 6}
print(s)  

Output
{1, 2, 3, 4, 5, 6}

This operation is equivalent to using the update() method.

Using union() 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.

Python
s1 = {1, 2, 3}
s2 = s1.union({4, 5, 6})
print(s2)  

Output
{1, 2, 3, 4, 5, 6}

Next Article

Similar Reads