Python Set update() (original) (raw)

Last Updated : 28 Apr, 2025

**update() method add multiple elements to a set. It allows you to modify the set in place by adding elements from an iterable (like a list, tuple, dictionary, or another set). The method also ensures that duplicate elements are not added, as sets inherently only contain unique elements. **Example:

Python `

s = {1, 2, 3}

s.update([3, 4, 5]) print(s)

`

Syntax of update()

set.update(*others)

Examples of update()

**Example 1: We can use **update() to add all elements from one set to another. Any duplicate elements will be ignored.

Python `

d1 = {'a': 1, 'b': 2} d2 = {'b': 3, 'c': 4}

d1.update(d2) print(d1)

`

Output

{'a': 1, 'b': 3, 'c': 4}

**Explanation: Since 3 is present in both sets, but it only appears once in the updated set1 because sets don’t allow duplicates.

**Example 2: We can also pass a list (or any iterable) to update() to add its elements to the set.

Python `

d1 = {'a': 1, 'b': 2} d1.update([('c', 3), ('d', 4)]) print(d1)

`

Output

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

**Explanation: update() method is called on d1 with the iterable [('c', 3), ('d', 4)], which adds the key-value pairs 'c': 3 and 'd': 4 to **d1.

**Example 3: You can update a set with multiple iterables in a single operation.

Python `

d1 = {'a': 1, 'b': 2} d1.update(c=3, d=4) print(d1)

`

Output

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

**Explanation: update() adds the key-value pairs 'c': 3 and 'd': 4 to **d1, creating new keys with the specified values.

**Example 4: update() method can also be used to add individual characters from a string to the set.

Python `

s1 = {1, 2, 3} s1.update("hello") print(s1)

`

Output

{1, 2, 3, 'e', 'l', 'h', 'o'}

**Explanation: Each character in the string "hello" is treated as a unique element and added to the set. Duplicates (like 'l') are ignored.