Python Set copy()
Python Set copy() method
Python Set copy() method returns a shallow copy of the original set.
In this tutorial, you will learn how to use Python Set copy() method, with syntax and different usage scenarios, with example programs.
Syntax of Set copy()
The syntax to call copy() method on a set is
set.copy()
Parameters
Set copy() method takes no parameters.
Return value
copy() method returns a set object. The returned set contains shallow copy of the original set.
Examples
1. Copying given Set to another in Python
In this example, we shall copy the contents of a set set_1 into another variable set_2.
Also, we shall modify the copied set and observe the contents of both the original and copied set.
Python Program
# Take a set
set_1 = {32, 56, 19}
# Copy set to another
set_2 = set_1.copy()
print('set 1:', set_1)
print('set 2:', set_2)
# Make some modifications to copies set
set_2.add(47)
print('\nafter modifications')
print('set 1:', set_1)
print('set 2:', set_2)
Output
set 1: {32, 56, 19}
set 2: {32, 56, 19}
after modifications
set 1: {32, 56, 19}
set 2: {32, 56, 19, 47}
The original set is unchanged.
2. Making multiple copies of given Set in Python
You can copy a set to one or more variables in a single statement. In this example, we shall initialize a set and copy it to two variables.
Python Program
# Take a set
set_1 = {32, 56, 19}
# Copy set to another
set_2 = set_3 = set_1.copy()
print('set 1:', set_1)
print('set 2:', set_2)
print('set 3:', set_3)
Output
set 1: {32, 56, 19}
set 2: {32, 56, 19}
set 3: {32, 56, 19}
Summary
In this Python Set Tutorial, we learned how to use copy() method of set class in Python, with the help of well detailed example programs.