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 frozenset()
Python super()
Python Program to Find All File with .txt Extension Present Inside a Directory
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Recursion
Python Program to Check the File Size
Python Program to Find HCF or GCD
Python Program to Add Two Numbers
Deep Learning in Python - LazyProgrammer
Python hex()
Python Program to Illustrate Different Set Operations
Python String rstrip()
Python Dictionary copy()
Python Program to Return Multiple Values From a Function
Python Program to Shuffle Deck of Cards
JavaScript Map and Set
Node.js vs Python for Backend Development
Deep Learning with Python - Francois Cholletf
Python int()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Compute all the Permutation of the String
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python complex()
Python Program to Display the multiplication Table
Python String rjust()
Python Program to Merge Two Dictionaries
Python Program to Remove Duplicate Element From a List
Python String istitle()
Python Program to Convert Decimal to Binary Using Recursion
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Check Armstrong Number
Python String split()