Python Set Copy: How to Copy Set

Python set copy() method copies the complete set of items into a completely new set.

Python Set Copy

Python Set copy() is a built-in method to copy a shallow copy of the set. The copy() method copies the set. Before knowing copy(), let me tell you that we can copy a set to another set using the “=” operator also.

But there is some problem with this method. If we modify the new set, the older one is changed. So, if we do not want to modify the original set, we should use the Python set() method.

Syntax

new_set = original_set.copy()

The new_set is the set you want to copy, and the original_set is the old set you want to keep unchanged.

Return Value

The set.copy() method does not return any value; it just copies the original set to a new set.

See the following code example.

# app.py

# Writing char by char in a set
set1 = {'C', 'o', 'd', 'i', 'n', 'g'}

print("Before copy the set is: ", set1)
# Now we will copy this set to a new set named Set2
# Using = operator
set2 = set1
print("The new set is: ", set2)

# Now we will modify the new set
set2.add('H')
set2.add('i')

# Printing both the set
print("After copying Old set is: ", set1)
print("After copying New set is: ", set2)

Output

Before copy the set is:  {'o', 'd', 'n', 'C', 'g', 'i'}
The new set is:  {'o', 'd', 'n', 'C', 'g', 'i'}
After copying Old set is:  {'o', 'd', 'n', 'C', 'H', 'g', 'i'}
After copying New set is:  {'o', 'd', 'n', 'C', 'H', 'g', 'i'}

So, in this example, we can see that the original set is also modified when we modify the new set. So, let’s understand copy() method, where we can keep our original set unchanged.

Example 2

# app.py

# Writing char by char in a set
set1 = {'C', 'o', 'd', 'i', 'n', 'g'}

print("Before copy the set is: ", set1)
# Now we will copy this set to a new set named Set2
# Using copy() method
set2 = set1.copy()
print("The new set is: ", set2)

# Now we will modify the new set
set2.add('H')
set2.add('i')

# Printing both the set
print("After copying Old set is: ", set1)
print("After copying New set is: ", set2)

Output

Before copy the set is:  {'d', 'g', 'n', 'i', 'o', 'C'}
The new set is:  {'i', 'd', 'g', 'o', 'n', 'C'}
After copying Old set is:  {'d', 'g', 'n', 'i', 'o', 'C'}
After copying New set is:  {'i', 'H', 'd', 'g', 'o', 'n', 'C'}

So, in this example, we can see that though we have made changes to our new set, the old set remains unchanged. This is the advantage of a set copy() method.

See also

Python set add()

Python set clear()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.