Python Set
Python Set copy() method is used make a copy of the existing set.
copy() method creates and returns a new set with the same contents as that of original set.
In this tutorial, we will learn how to use copy() method, with the help of different usage scenarios.
Example 1: Copy Python Set
In this example, we shall copy a contents of a set into another variable.
Also, we shall modify the copied set and observe the contents of both the original and copied set.
Python Program
#initialize set
set_1 = {32, 56, 19}
#copy set
set_2 = set_1.copy()
print('set 1:', set_1)
print('set 2:', set_2)
#some modifications
set_2.add(47)
print('\nafter modifications')
print('set 1:', set_1)
print('set 2:', set_2)
Run 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.
Example 2: Copy Set to Multiple Variables
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
#initialize set
set_1 = {32, 56, 19}
#copy set
set_2 = set_3 = set_1.copy()
print('set 1:', set_1)
print('set 2:', set_2)
print('set 3:', set_3)
Run Output
set 1: {32, 56, 19}
set 2: {32, 56, 19}
set 3: {32, 56, 19}
Summary
In this tutorial of Python Examples, we learned how to use copy() method of set class in Python, with the help of well detailed example programs.