Python Set copy() Method

Copies the set shallowly

Usage

The copy() method returns the Shallow copy of the specified set.

Syntax

set.copy()

Basic Example

# Copy set 'S' to 'x'
S = {'red', 'green', 'blue'}
x = S.copy()
print(x)
# Prints {'blue', 'green', 'red'}

copy() vs Assignment statement

Assignment statement does not copy objects. For example,

old_Set = {'red', 'green', 'blue'}
new_Set = old_Set
new_Set.remove('red')
print(old_Set)
# Prints {'blue', 'green'}
print(new_Set)
# Prints {'blue', 'green'}

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.

set copy method vs assignment statement

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 = {'red', 'green', 'blue'}
new_Set = old_Set.copy()
new_Set.remove('red')
print(old_Set)
# Prints {'blue', 'green', 'red'}
print(new_Set)
# Prints {'blue', 'green'}