How to Add Elements in a Set in Python

Published on Aug. 22, 2023, 12:16 p.m.

To add an element to a set in Python, you can use the add() function. The add() function adds the specified element to the set. Here’s an example:

my_set = {'apple', 'banana', 'cherry'}
my_set.add('orange')
print(my_set)   # Output: {'banana', 'orange', 'apple', 'cherry'}

In this example, we first define a set my_set containing three string elements. We then use the add() function to add the string 'orange' to the set. Finally, we print the resulting set to the console, which contains all the original elements plus the new element.

Note that the add() function only adds the element to the set if it is not already present in the set. If you want to add multiple elements to a set at once, you can use the update() function instead.

Lastly, if you want to add elements to a set from another iterable, such as a list, you can use the update() function with that iterable as a parameter.

Tags:

related content