VOOZH about

URL: https://www.geeksforgeeks.org/python/python-set-update/

⇱ Python Set update() - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Set update()

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:


Output
{1, 2, 3, 4, 5}

Syntax of update()

set.update(*others)

  • *others: One or more iterables (sets, lists, tuples, strings, etc.) from which elements will be added to the set.

Examples of update()

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


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.


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.


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.


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.

Comment
Article Tags: