The set
is one of the core data types in Python, it represents a collection of non-ordered, unique elements. Just like lists, sets are mutable, meaning that we can perform operations on them in-place.
The set.update()
method is used to add multiple distinct elements into a set. Its syntax is as shown below:
set.update(iterable)
iterable |
An iterable containing the elements to be added to the set. We can also pass multiple iterables. |
The function adds distinct elements from the iterable into the set. It returns None
.
Consider the following example:
# a set of cities
cities = {'Tokyo', 'Denver', 'Nairobi'}
#a list with the elements to be added
L = ['Berlin', 'Helsinki', 'Manilla']
#add the elements from the list into the set.
cities.update(L)
#print the set
print(cities)
In the above example we updated the sets using elements from a list, we can also use any other iterable such as tuples, dictionaries, range or even other sets. In the following example we pass most iterables as the argument to the update()
function.
#the set
nums = {0, 1, 2}
# a tuple with elements
mytuple = (3, 4, 5)
#a set with elements
myset = {6, 7, 8, 9}
#update the 'nums' set with two iterables
nums.update(mytuple, myset)
#print the set
print(nums)
Since sets can only contain unique elements, if the iterable given as the argument has an element that is already in the set; that element will be ignored.
#the set
nums = {1, 2, 3, 4}
# a list
L = [3, 4, 5]
#update the set
nums.update(L)
#print the set
print(nums)