AppDividend
Latest Code Tutorials

Python Set Copy() Method Example Tutorial

0

Python Set copy() is an inbuilt method that is used to copy a shallow copy of the set. The copy() method copies the set. Before knowing copy(), let me tell that we can copy a set to another set using the ‘=’ operator also. But there is some problem with this method. Like, if we modify the new set the older one is modified. So, if we do not want to modify the original set, we should use the Python set() method.

Python Set Copy()

The method is used to copy the complete set items into a completely new set.

Syntax

new_set = original_set.copy()

Here, the new_set is the set in which you want to copy and original_set is the old set which 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 modified the new set.

Now, 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 Reply

Your email address will not be published.

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