Home »
Python
Python Set copy() Method (with Examples)
Python Set copy() Method: In this tutorial, we will learn about the copy() method of the set class with its usage, syntax, parameters, return type, and examples.
By IncludeHelp Last updated : June 14, 2023
Python Set copy() Method
The copy() is an inbuilt method of the set class that is used to copy the set, it returns a set that contains all elements of this set. The method is called with this set and returns a copy of it.
Syntax
The following is the syntax of copy() method:
set_name.copy()
Parameter(s):
The following are the parameter(s):
- None - It does not accept any parameter.
Return Value
The return type of this method is <class 'set'>, it returns a set contains the copy of this set.
Example 1: Use of Set copy() Method
# Python Set copy() Method (with Examples)
# declaring a set
cities = {"New Delhi", "Mumbai", "Indore", "Gwalior"}
# creating another set by using
# copy() method
x = cities.copy()
# printing both sets
print("cities: ", cities)
print("x: ", x)
Output
cities: {'New Delhi', 'Mumbai', 'Indore', 'Gwalior'}
x: {'New Delhi', 'Mumbai', 'Indore', 'Gwalior'}
Example 2: Use of Set copy() Method
# declaring a set
digits = {10, 20, 30}
# printing original set
print("Original set:", digits)
# copying set
res = digits.copy()
# printing copied set
print("Copied set:", res)
# adding an element to the copied set
res.add(40)
# printing both sets after adding
# an element
print("\nAfter adding element...")
print("Original set:", digits)
print("Copied set:", res)
Output
Original set: {10, 20, 30}
Copied set: {10, 20, 30}
After adding element...
Original set: {10, 20, 30}
Copied set: {40, 10, 20, 30}