In some cases, programmers wish to have multiple copies of a certain set to perform various tasks. The python set copy function gives the shallow copy of the set as the output. A shallow copy means that any changes made to the new set will not be reflected in the original set.
Syntax:
set_name.copy()
copy() Parameters
The python set copy function does not take any parameters as input from the user,
Return Value from copy()
The python set copy method returns a shallow copy of the given set as the output.
Example 1: How the copy() method works for sets?
Look at the example given below to understand how the set copy() works in the python programming language. Any changes made to the new set will not be reflected in the original set.
Source Code:
numbs = {1, 2, 3, 4}
new_numbs = numbs.copy()
new_numbs.add(5)
print('original_numbers set: ', numbs)
print('new_numbers set: ', new_numbs)
Output
original_numbers set: {1, 2, 3, 4}
new_numbers set: {1, 2, 3, 4, 5}
How do you copy a set in Python?
Python has a built-in function called set copy() that is used to create a shallow copy of the desired set.
For example:
s1 = {'h', 'e', 'l', 'l', 'o'}
s2 = s1.copy()
# before adding
print ('before adding the element: ')
print ('set 1: ',s1)
print ('set 2: ', s2)
s2.add('f')
# after adding
print ('after adding element: ')
print ('set 1: ',s1)
print ('set 2: ', s2)
Output:
before adding the element:
set 1: set(['h', 'e', 'l', 'l', 'o'])
set 2: set(['h', 'e', 'l', 'l', 'o'])
after adding the element:
set 1: set(['h', 'e', 'l', 'l', 'o'])
set 2: set(['h', 'e', 'l', 'l', 'o' 'f'])
What is the use of copy () in Python?
The copy() in python is used to create a copy of the list as required by the user. As the copied list is shallow, any changes made to the new list will not be reflected in the original list.
How do you deep copy an object in Python?
Deep copy is a recursive copying procedure. The technique starts by creating a new collection object and then populating it with copies of the original’s child objects in a recursive order. In a deep copy, one object’s copy is copied into another object. Any changes made to a copy of an object will not affect the original.
Source Code:
import copy
li1 = [1, 2, [3,5], 4]
li2 = copy.deepcopy(li1)
print ("The original elements before deep copying")
for i in range(0,len(li1)):
print (li1[i],end=" ")
print("\r")
li2[2][0] = 7
print ("After deep copying ")
for i in range(0,len( li1)):
print (li2[i],end=" ")
print("\r")
print ("The original elements after deep copying")
for i in range(0,len( li1)):
print (li1[i],end=" ")
Output:
The original elements before deep copying
1 2 [3, 5] 4
After deep copying
1 2 [7, 5] 4
The original elements after deep copying
1 2 [3, 5] 4
How do you copy a string in Python?
In python, users can copy a string with the help of the slicing method:
Source Code:
str1="hello brother"
str2=str1[:]
print(str2)
Output:
hello brother
Leave a Reply