Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Set update() method



The Python Setupdate() method is used with sets to modify the set by adding elements from another iterable or set. It takes an iterable such as another set, list or tuple as an argument and adds its elements to the calling set. If any element in the iterable is already present in the set it won't be added again.

This method allows for the efficient merging of multiple sets or iterables into one by making it useful for combining data structures and eliminating duplicates. The original set is modified in place and the method returnsNone indicating that the set has been updated.

Syntax

Following is the syntax and parameters of Python Setupdate() method −

set.update(iterable)

Parameter

This method accepts an iterable such as a list, tuple or another set containing elements to be added to the set.

Return value

This method does not return any value.

Example 1

Following is the example which shows updating the original set with another set of elements −

# Define a setset1 = {1, 2, 3}set2 = {3, 4, 5}# Update set1 with elements from set2set1.update(set2)print(set1)

Output

{1, 2, 3, 4, 5}

Example 2

This example shows how to update a set with elements of different types of iterables −

# Define a setmy_set = {1, 2, 3}my_iterable = [3, (4, 5), 6]# Update the set with elements from the iterablemy_set.update(my_iterable)print(my_set)

Output

{1, 2, 3, 6, (4, 5)}

Example 3

This example shows how to update a set with elements from nested sets −

# Define a setmy_set = {1, 2}nested_set = {3, 4, (5, 6), 7 , 8}# Update the set with elements from the nested setmy_set.update(nested_set)print(my_set)

Output

{1, 2, 3, 4, (5, 6), 7, 8}

Example 4

In this example we are updating with an empty iterable which does not change the set −

# Define a setmy_set = {1, 2, 3}empty_iterable = []# Update the set with an empty iterablemy_set.update(empty_iterable)print(my_set)

Output

{1, 2, 3}
python_set_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp