Python Set update() Method
The update() method in Python adds multiple elements to a set from an iterable, such as a list, tuple, string, or another set.
Syntax
set.update(*iterables)
Parameters
iterables (Required): One or more iterables (lists, tuples, sets, or strings) whose element you want to add to the set.
Return Value
Returns None. It modifies the list in-place.
Key Characteristics
- In-Place Modification: It changes the original set. It doesn’t return a new set (it returns
None). - Uniqueness: If an element already exists in the set, the
update()method ignores it (no duplicates are added). - Flexibility: You can pass multiple iterables, separated by commas, in a single call.
Example 1: Add elements from a list
fruits = {"apple", "banana"}
fruits.update(["mango", "pineapple"])
print(fruits) # Output: {'apple', 'banana', 'pineapple', 'mango'}
Python sets are unordered, so the elements may appear in a different order each time you print them.
Example 2: Add elements from multiple iterables
numbers = {1, 2}
my_list = [5, 10]
my_tuple = (20, 30)
# Update using both a list and a tuple at once
numbers.update(my_list, my_tuple)
print(numbers) # Output: {1, 2, 5, 10, 20, 30}
Example 3: Adding a Duplicate Element
Duplicate elements are automatically ignored because sets store only unique values.
fruits = {"apple", "banana"}
fruits.update(["banana", "mango"])
print(fruits) # Output: {'banana', 'mango', 'apple'}
Example 4: Add characters from a string
You can use the update() method to add individual characters from a string to a set.
letters = {"a", "b"}
letters.update("bc")
print(letters) # Output: {'b', 'a', 'c'}
Example 5: Add keys from a dictionary
The update() method adds only a dictionary’s keys to a set, not its values.
my_set = {"1", "2"}
my_dict = {"a": 5, "b": 10}
my_set.update(my_dict)
print(my_set) # Output: {'b', '1', '2', 'a'}