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 for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Namespace and Scope
Python complex()
Python Program to Display Powers of 2 Using Anonymous Function
Python String upper()
Python time Module
Python Program to Get the Full Path of the Current Working Directory
Python Sets
Python Program to Differentiate Between type() and isinstance()
Python File I/O Operation
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python *args and **kwargs
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Represent enum
Python Dictionary items()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Machine Learning with Python for everyone - Mark E.Fenner
Python oct()
Python Program to Convert Celsius To Fahrenheit
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Get the Class Name of an Instance
Python Function Arguments
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python @property decorator
Python String ljust()
Python hex()
Node.js vs Python for Backend Development
Python String encode()
Python Set intersection()
Python Data Types
Python datetime
Python String zfill()