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 Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Convert Kilometers to Miles
Python Program to Append to a File
Python String zfill()
Python Decorators
Python Program to Find the Sum of Natural Numbers
Python Matrices and NumPy Arrays
Python String islower()
Python Generators
Python Keywords and Identifiers
Python all()
Python Program to Randomly Select an Element From the List
Python super()
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Create Pyramid Patterns
Python Set difference()
Python type()
Python Program to Transpose a Matrix
Python String isalnum()
Python String isnumeric()
Python Program to Check if a Key is Already Present in a Dictionary
Python Dictionary setdefault()
Python Global Keyword
Python repr()
Python Program to Differentiate Between type() and isinstance()
Python Program to Check the File Size
Python Tuple count()
Python pass statement
Python chr()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String rpartition()
Python Inheritance