English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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()
It does not take any parameters.
The copy() method modifies the given set. It does not return any value.
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}