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:
Deep Learning in Python - LazyProgrammer
Python Dictionary setdefault()
Python String rindex()
Python Program to Display the multiplication Table
Python List clear()
Python Set intersection_update()
Python Inheritance
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python type()
Python @property decorator
Python String format()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Set issubset()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Modules
Python String swapcase()
Python String rfind()
Python compile()
Python List index()
Python List reverse()
Python getattr()
Python Dictionary items()
Python Program to Find Factorial of Number Using Recursion
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python __import__()
Python Program to Copy a File
Python Program to Check If a String Is a Number (Float)
Python String isspace()
Python String endswith()
Python Program to Find Numbers Divisible by Another Number
Python Global Keyword
Python Statement, Indentation and Comments