copy() of Sets in Python

copy() of Sets in Python

The copy() method returns the copy of the set in python.

When we use “=” sign to copy the set, if we modify the copied set then the changes are also reflected back in the original set. So here we have to create a shallow copy of the set such that when we modify something in the copied set, changes are not reflected back in the original set.

Copy of sets in python

copy() of Sets

In Python, you can create a copy of a set using the copy() method. The copy() method creates a shallow copy of the set, which means it duplicates the elements of the set into a new set, but it does not create copies of the elements themselves.

Python Set copy()

Syntax :


set2=set1.copy()


Return Type :

The copy() method returns a shallow copy of the set in python.

Run
#copy() in python set

set1 = {1, 2, 3, 4, 5 }
print("Set 1 : ",set1)

#all the values of set1 is copied to the set2
set2=set1.copy()
print("Set 2 : ",set2)

#modifying set2
set2.add(10)
print("After adding new element in set2")

#changes is reflected in only set2 not in set1
print("Set 1 : ",set1)
print("Set 2 : ",set2)
Output :

Set 1 :  {1, 2, 3, 4, 5}
Set 2 :  {1, 2, 3, 4, 5}

After adding new element in set2
Set 1 :  {1, 2, 3, 4, 5}
Set 2 :  {1, 2, 3, 4, 5, 10}

In the above code the modification in copied set is only reflected in copied set.

See the below example to understand the difference between copy() and “=”.

Run
# "=" in python set

set1 = {1, 2, 3, 4, 5 }
print("Set 1 : ",set1)

#all the values of set1 is copied to the set2
set2 = set1
print("Set 2 : ",set2)

#modifying set2
set2.add(10)
print("After adding new element in set2")

#changes is reflected in both set2 and set1
print("Set 1 : ",set1)
print("Set 2 : ",set2)
Output :

Set 1 :  {1, 2, 3, 4, 5}
Set 2 :  {1, 2, 3, 4, 5}

After adding new element in set2
Set 1 :  {1, 2, 3, 4, 5, 10}
Set 2 :  {1, 2, 3, 4, 5, 10}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription