The copy() method returns a copy of the set.
Example
copy() Syntax
The syntax of copy() method is:
set.copy()
Here, the items of the set are copied.
copy() Parameters
The copy() method doesn't take any parameters.
copy() Return Value
The copy() method returns
- the copy of the set
Example 1: Python Set copy()
Output
Original Names: {'Marie', 'John', 'Charlie'}
Copied Names: {'Marie', 'John', 'Charlie'}
In the above example, we have used the copy() method to copy the set names. The items of names are copied to new_names.
Here, new_names is the exact copy of names.
Example 2: Copy Set using = operator
We can also copy the set by simply using the = operator.
Output
Original Names: {'John', 'Marie', 'Charlie'}
Copied Names: {'John', 'Marie', 'Charlie'}
In the above example, we have used = operator to copy the set names. The items of names are copied to new_names. Here, the = operator works exactly like the copy() method.
Example 3: Add items to the set after copy()
We can also modify the copied set using different methods.
Output
numbers: {1, 2, 3, 4}
new_numbers: {1, 2, 3, 4, 5}
In the above example, we have modified the copied set new_numbers using add() method. Here, the copied set is different from the original set because we have added new item 5 to it.