Python Set update()

Example


update() Syntax

The syntax of the update() method is:

A.update(B)

Here, A is a set and B can be any iterable like list, set, dictionary, string, etc.


update() Parameter

The update() method can take any number of arguments. For example,

A.update(B, C, D)

Here,

  • B, C, D - iterables whose items are added to set A

update() Return Value

The update() method doesn't return any value.


Example 1: Python Set update()

Output

Original A: {1, 3, 5}
A after update() {0, 1, 2, 3, 4, 5, 6}

In the above example, we have used the update() method to add items of set B and C to A and update A with the resulting set.

Here, initially set A only has 3 items. When we call update(), the items of B and C are added to set A.


Example 2: update() to add String and Dictionary to Set

Output

Set and strings: {1, 3, 'o', 'd'}
Set and dictionary keys: {'lock', 2, 4, 'key'}

In the above example, we have used the update() method to add string and dictionary to the set.

The method breaks down the string into individual characters and adds them to the set number1. Similarly, it adds the keys of the dictionary to the set number2.

Note: If dictionaries are passed to the update() method, the keys of the dictionaries are added to the set.