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 ord()
Python String isdigit()
Python String join()
Python Program to Find the Size (Resolution) of a Image
Python hash()
Python Program to Check If Two Strings are Anagram
Python Set remove()
Python Program to Display Powers of 2 Using Anonymous Function
Python Matrices and NumPy Arrays
Python Program to Find Hash of File
Python String casefold()
JavaScript Map and Set
Python Program to Display the multiplication Table
Python Program to Remove Punctuations From a String
Python hex()
Python String isalnum()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Count the Number of Digits Present In a Number
Python all()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python List
Python Multiple Inheritance
Python Program to Check Whether a String is Palindrome or Not
Python oct()
Python String upper()
Python String isspace()
Python Errors and Built-in Exceptions
Python Set issuperset()
Python abs()
Python Dictionary values()
Python if...else Statement
Python format()