Join Regular Classroom : Visit ClassroomTech

Python Set – copy() Method

It is a method in python that copies all the content of the set to a new set. It returns a new set, it doesn’t modify the old set. Any modification of the new set (copied set) will not affect the old set. This method doesn’t take any parameters in it.

Syntax:
new_set = old_set.copy()

Also Read: Python Set – symmetric_difference() Method

Example 1:

# Python code to understand copy() method in set
# www.codewindow.in

s = {"Name", "codewindow", "Country", "India"}
new = s.copy()
print(new)

Output:

{'Name', 'codewindow', 'Country', 'India'}

Explanation:
It copied the existing set (s) to a new set (new) and returns it.

Example 2:

# Python code to understand copy() method in set
# www.codewindow.in

s = {"Name", "codewindow", "Country", "India"}
new = s.copy()
new.update({"State"})
print("new_set",new)
print("old_set",s)

Output:

new_set {'State', 'Name', 'India', 'Country', 'codewindow'}
old_set {'India', 'Country', 'codewindow', 'Name'}

Explanation:
Here, any changes to the new set did not affect the old set as you can clearly see. The iterable “State” was not added in the old set but only added to the new set.


Follow Us

You Missed

Also Checkout