Python Set copy()

The copy() method returns a copy of the set.

Example

numbers = {1, 2, 3, 4}

# copies the items of numbers to new_numbers new_numbers = numbers.copy()
print(new_numbers) # Output: {1, 2, 3, 4}

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()

names = {"John", "Charlie", "Marie"}

# items of names are copied to new_names new_names = names.copy()
print('Original Names: ', names) print('Copied Names: ', new_names)

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.

names = {"John", "Charlie", "Marie"}

# copy set using = operator new_names = names
print('Original Names: ', names) print('Copied Names: ', new_names)

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.

numbers = {1, 2, 3, 4}
new_numbers = numbers

print('numbers: ', numbers)

# add 5 to the copied set new_numbers.add(5)
print('new_numbers: ', new_numbers)

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.

Did you find this article helpful?