English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic Python Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Objects and Classes in Python

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Usage and examples of Python set copy()

Méthodes de collection en Python

The copy() method copies the set.

In Python, you can use the = operator to copy a set. For example:

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

The problem with copying the set in this way is that if you modify the numbers set, the new_numbers set will also be modified.

numbers = {1, 2, 3, 4}
new_numbers = numbers
new_numbers.add('5)
print('numbers: ', numbers)
print('new_numbers: ', new_numbers)

When running the program, the output is:

numbers:  {1, 2, 3, 4, '5}
new_numbers:  {1, 2, 3, 4, '5}

However, if you need to keep the original set unchanged while modifying the new set, you can use the copy() method.

The syntax of copy() is:

set.copy()

Parameters of copy()

It does not take any parameters.

Return value of copy()

The copy() method modifies the given set. It does not return any value.

Example1:How to use the copy() method in set?

numbers = {1, 2, 3, 4}
new_numbers = numbers.copy()
new_numbers.add('5)
print('numbers: ', numbers)
print('new_numbers: ', new_numbers)

When running the program, the output is:

numbers:  {1, 2, 3, 4}
new_numbers:  {1, 2, 3, 4, '5}

Méthodes de collection en Python