Set copy() Method in Python

Python Set copy() Method

The copy() method is used to create a shallow copy of a set. The new set will contain the same elements as the original set, but they will be in a separate memory location. Any modifications made to the copied set will not affect the original set, and vice versa.

Syntax of the copy() method:

new_set = your_set.copy()

Parameters:

  • your_set: This is the set that you want to copy.

Example:

# Creating a set with some elements
fruits = {'apple', 'banana', 'orange'}

# Creating a shallow copy of the 'fruits' set
fruits_copy = fruits.copy()

# Modifying the copied set
fruits_copy.add('grape')

print(fruits)      # Output: {'apple', 'banana', 'orange'} (original set remains unchanged)
print(fruits_copy) # Output: {'apple', 'banana', 'orange', 'grape'}

In this example, we created a set called fruits with three elements. Then, we created a shallow copy of the fruits set called fruits_copy. After adding a new element 'grape' to fruits_copy, we printed both the original fruits set and the copied fruits_copy set. As you can see, only the copied set was modified, while the original set remained unchanged.

Keep in mind that the copy is shallow, so if the set contains mutable objects (e.g., other sets, lists, or dictionaries), those objects will still reference the same memory locations in both the original set and the copied set. Therefore, changes made to the elements within those mutable objects will affect both sets. If you need a deep copy (a completely independent copy), you can use the copy.deepcopy() function from the copy module.