Set update() Method in Python

Python Set update() Method

The update() method is used to modify the original set by adding elements from another iterable (e.g., set, list, tuple, etc.) into it. It updates the original set in place and adds the elements from the specified iterable to the set.

Syntax of the update() method:

your_set.update(iterable)

Parameters:

  • your_set: The set to which you want to add elements.
  • iterable: The iterable (e.g., set, list, tuple, etc.) containing elements to be added to the set.

Example:

# Creating a set of fruits
fruits = {'apple', 'banana', 'orange'}

# Adding elements from a list to the set using update()
fruits_list = ['kiwi', 'grape']
fruits.update(fruits_list)

print(fruits)  # Output: {'apple', 'banana', 'orange', 'kiwi', 'grape'} (list elements are added to the set)

# Adding elements from another set to the set using update()
more_fruits = {'mango', 'pineapple'}
fruits.update(more_fruits)

print(fruits)  # Output: {'kiwi', 'banana', 'orange', 'apple', 'mango', 'pineapple', 'grape'} (new set elements are added)

In this example, the update() method is used to add elements from a list (fruits_list) and another set (more_fruits) to the original set fruits. After each update() operation, the set fruits is modified and contains the new elements.

Keep in mind that when using the update() method, duplicates are automatically removed, as sets only allow unique elements. If an element already exists in the set, it won't be duplicated.