The Set copy() method creates a Shallow copy of the set.
Syntax
my_set.copy()copy() Parameters
Python Set copy() method does not take any parameters.
copy() Return Value
Python Set copy() method returns a new set. It does not modify the original set.
Examples
Example 1: Copy a Set with copy()
Consider this example in which:
original_set.copy()creates a shallow copy oforiginal_set.- When a string in the
copied_setis modified, it does not affectoriginal_setbecause the values in the sets are references to the same objects.
original_set = {'Tom', 'Ryan', 'David'}
copied_set = original_set.copy()
print("Original set:", original_set)
print("Copied set:", copied_set)
copied_set.add('Anna')
print("Original set after modification:", original_set)
print("Copied set after modification:", copied_set)output
Original set: {'David', 'Tom', 'Ryan'}
Copied set: {'David', 'Tom', 'Ryan'}
Original set after modification: {'David', 'Tom', 'Ryan'}
Copied set after modification: {'David', 'Tom', 'Ryan', 'Anna'}Example 2: Copy a Set with Mixed Types with copy()
The copy() method allows to create a shallow copy of a set containing mixed types:
original_set = {1, "two", (3, 4)}
copied_set = original_set.copy()
print("Original Set:", original_set)
print("Copied Set:", copied_set)output
Original Set: {1, 'two', (3, 4)}
Copied Set: {1, 'two', (3, 4)}copy() vs Assignment statement
- When the
copy()method is used, a new set is created which is filled with a copy of the references from the original set. - When the
=operator is used, a new reference to the original set is created.
For example, an assignment statement does not copy objects.
old_set = {'Ryan', 'David', 'Tom'}
new_set = old_set
new_set.add('Anna')
print(old_set) # Output: {'Anna', 'Ryan', 'David', 'Tom'}
print(new_set) # Output: {'Anna', 'Ryan', 'David', 'Tom'}output
{'Anna', 'Ryan', 'David', 'Tom'}
{'Anna', 'Ryan', 'David', 'Tom'}When you execute new_set = old_set, you don't actually have two sets. The assignment just makes the two variables point to the one set in memory.
So, when you change new_set, old_set is also modified. If you want to change one copy without changing the other, use copy() method.
old_set = {'Ryan', 'David', 'Tom'}
new_set = old_set
new_set.add('Anna')
print(old_set) # Output: {'Anna', 'Tom', 'Ryan', 'David'}
print(new_set) # Output: {'Anna', 'Tom', 'Ryan', 'David'}output
{'Anna', 'Tom', 'Ryan', 'David'}
{'Anna', 'Tom', 'Ryan', 'David'}