article
menu_book Article

Copying Sets in Python: Creating Duplicates of Sets

Get The Most Affordable Hosting in the World!

Starting at just $1.87/month — fast, reliable & secure. Free CDN included.

rocket_launch Get Started

The copy() method in set class creates a shallow copy of a set object.

Syntax

set.copy()

Return Value

The copy() method returns a new set which is a shallow copy of existing set.

Example

 
lang1 = {"C", "C++", "Java", "Python"} print ("lang1: ", lang1, "id(lang1): ", id(lang1)) lang2 = lang1.copy() print ("lang2: ", lang2, "id(lang2): ", id(lang2)) lang1.add("PHP") print ("After updating lang1") print ("lang1: ", lang1, "id(lang1): ", id(lang1)) print ("lang2: ", lang2, "id(lang2): ", id(lang2))

Output

It will produce the following output −

lang1: {'Python', 'Java', 'C', 'C++'} id(lang1): 2451578196864
lang2: {'Python', 'Java', 'C', 'C++'} id(lang2): 2451578197312
After updating lang1
lang1: {'Python', 'C', 'C++', 'PHP', 'Java'} id(lang1): 2451578196864
lang2: {'Python', 'Java', 'C', 'C++'} id(lang2): 2451578197312



The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

favorite 1 Users Found This Useful  ·  1 Votes

Powered by WHMCompleteSolution