Python Set update() Method with examples

Python Set update

Now, we are going to learn about the update method. Using the update method, we can update our current set, by adding the elements from another set, or some other iterable. For example, if we have set1 = {1, 2, 3}, and we have set2 = {3, 4, 5}, then doing set1.update(set2), will update the set1, by inserting the elements from the set2, and also if the element is already present there in the set, it is not added again. So, the set is updated with the appropriate values.

Let’s have a look at a simple program, which tries to demonstrate the same thing.

Python Set update() Method

As you can see in the above program, we have two sets, set1, and set2. Then we are trying to do set1.update(set2), so the set1 would be updated with the values from the set2. We can give some other iterable as well, as an argument. The thing is that set1 now contains the appropriate values.

Let’s have a look at the output in our case here –

{1, 3.1, 4.1, 41, 10, 11, 45, 29}

As you can see, set1 was updated with the items from set2. So, in this way, we can make use of the update method as and when required.  Remember that with the update method, one set is updated with the values of some other set, or some other iterable.  Let’s try to have a look at another program, in which, we would pass some iterable to the update method. Let’s have a look –

As you can see in the above program, we have a set, and then we are trying to update the set, with the values from a list. So, we are passing a list as an argument to the update method. After that, we are printing the set. So, we can simply find that set1 was updated with the values from the list. Let’s have a look at the output in our case.

{1, 3.1, 10, 11, 12, 16, 29, 41, 45}

As you can see, set1 is updated with the values from the list. So, as and when required, we can make use of the update method. Remember that with the update method, we can update a set with the values from some other set or iterable.