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 staticmethod()
Python Functions
Python Program to Swap Two Variables
Python Program to Reverse a Number
Python Program to Convert Bytes to a String
Python Program to Shuffle Deck of Cards
Python Program to Get Line Count of a File
Python globals()
Python super()
Python Deep Learning Cookbook - Indra den Bakker
Python slice()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python delattr()
Python Function Arguments
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python enumerate()
Python Object Oriented Programming
Python min()
Python Program to Find Factorial of Number Using Recursion
Python Inheritance
Python List copy()
Python memoryview()
Python Data Structures and Algorithms - Benjamin Baka
Python getattr()
Python Set difference_update()
Python Program to Measure the Elapsed Time in Python
Python Recursion
Python Set issubset()
Python String split()
Python String center()
Python String find()
Python String isnumeric()