Table of Contents
The copy() method returns a shallow copy of the set.
A set can be copied using = operator in Python. 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 is also modified.
numbers = {1, 2, 3, 4}
new_numbers = numbers
new_numbers.add(5)
print('numbers: ', numbers)
print('new_numbers: ', new_numbers)
Output
numbers: {1, 2, 3, 4, 5}
new_numbers: {1, 2, 3, 4, 5}
However, if you need the original set to be unchanged when the new set is modified, you can use the copy() method.
The syntax of copy() is:
set.copy()
1. copy() Parameters
It doesn’t take any parameters.
2. Return Value from copy()
The copy() method returns a shallow copy of the set.
3. Example 1: How the copy() method works for sets?
numbers = {1, 2, 3, 4}
new_numbers = numbers.copy()
new_numbers.add(5)
print('numbers: ', numbers)
print('new_numbers: ', new_numbers)
Output
numbers: {1, 2, 3, 4}
new_numbers: {1, 2, 3, 4, 5}
Related posts:
Python String isalpha()
Python String splitlines()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python type()
Python any()
Python String title()
Python input()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python delattr()
Python break and continue
Python range()
Python Program to Add Two Numbers
Python open()
Python Program to Find HCF or GCD
Python Program to Find ASCII Value of Character
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Find LCM
Python Operators
Python setattr()
Python Program to Find the Sum of Natural Numbers
Python Program to Find the Factors of a Number
Python Dictionary clear()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Package
Python frozenset()
Python getattr()
Python id()
How to Get Started With Python?
Python timestamp to datetime and vice-versa
Python Program to Check if a Number is Positive, Negative or 0
Python tuple()