Python set Method - copy()

https‮ww//:‬w.theitroad.com

The copy() method in Python is used to create a shallow copy of a set. The method returns a new set that contains the same elements as the original set.

The syntax for the copy() method is as follows:

new_set = set.copy()

Here, set refers to the set that needs to be copied, and new_set is the new set that contains the same elements as the original set.

Example:

# Creating a set
my_set = {1, 2, 3}

# Creating a copy of the set
new_set = my_set.copy()

# Displaying the original set
print(my_set)   # Output: {1, 2, 3}

# Displaying the copied set
print(new_set)   # Output: {1, 2, 3}

# Modifying the copied set
new_set.add(4)

# Displaying the modified set and original set
print(my_set)   # Output: {1, 2, 3}
print(new_set)   # Output: {1, 2, 3, 4}

In the above example, the copy() method is used to create a new set new_set that contains the same elements as the set my_set. The original set and the copied set are printed to show that they are the same. Then, the add() method is used to add the integer 4 to the copied set, while the original set remains unchanged. The modified and original sets are printed again to show the difference. It is important to note that the copy() method creates a shallow copy of the set, which means that the elements in the copied set are the same as the elements in the original set, but they may not be the same objects.