Python Sets Add Elements


In Python Sets, we can add items to a set using the add() method or the update() method.


Using add()

The add() method adds a single element to the set.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
# {1, 2, 3, 4}


Using update()

The update() method can add multiple elements to the set. You can pass any iterable (list, tuple, set, etc.) to update().

my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set)
# {1, 2, 3, 4, 5, 6}

You can also use update() with other iterables like strings, tuples, or even other sets.

Example with a string -

my_set = {1, 2, 3}
my_set.update("abc")
print(my_set)
# {1, 2, 3, 'a', 'b', 'c'}

Example with a tuple -

my_set = {1, 2, 3}
my_set.update((4, 5))
print(my_set)
# {1, 2, 3, 4, 5}

Example with another set -

my_set = {1, 2, 3}
my_set.update({4, 5, 6})
print(my_set)
# {1, 2, 3, 4, 5, 6}

These methods allow us to dynamically add elements to a set, maintaining its property of containing only unique elements.