vertopal.com_setassignment
vertopal.com_setassignment
pop, remove, discard, clear, and copy. Additionally, compare these methods with those you
have previously learned.
update() : This method will allow to add multiple arguments inside the update method in a
single stroke.
set1={1,2,3}
set2={4,5,6}
x=set1.update(set2)
x={1,2,3,4,5,6}
add() : This method will add only an element to the set at the end of set and does not allow
multiple parameters unlike update method
Eg
s1={1,2,3}
s2={4}
s1.append(s2)
output :
s1={1,2,3,4}
pop() : pop allows a random element from the set to be removed and it does not follow any
indexing order unless index is mentioned.
s1={1,2,3}
s1.pop()
remove() : This method will remove a specific element from the set by accessing a paricular
element and passing it as an argument inside parenthesis.
s1={67,87,90,900}
s1.remove(900)
output
s1={67,87,90}
discard() : This method will remove an element from set like remove method but does not
throw an error even when trying to discard non existing element from set unlike remove
which shows error.
s1={34,87,90,67,78}
s1.discard(90}
s1.discard(0)
output
s1={34,87,67,78}
s1={34,87,90,67,78}
cler() : This method is capable of clearing all elements inside a set and remains us an empty
set.
s1={45,90,80,78}
s1.clear()
output
s1={}
add() :
# add method
s1={90,89,87,88,98}
s1.add(99)
print(s1)
update() :
{0, 67, 70, 77, 88, 89, 90, 97, 98, 99, 56}
remove() :
# remove method
s1={78,34,90,98,79}
s1.remove(78)
print(s1)
discard() :
# discard method
s1={78,87,98,89,79,97}
s1.discard(97)
print(s1)
clear() :
s1={90,89,98,78,87,99}
s1.clear()
print(s1)
set()
pop() :
# pop method
s1={78,87,89,98,90,99}
s1.pop()
print(s1)
copy() : This method will copy the elements of a set to another set by using copy() but address
will get changed of newer set.
Below is example
s1={99,98,97,96,91}
s2=s1.copy()
print(s2,id(s2),type(s2),sep="\n")
Methods like add() and update() are for adding elements, but update() works with multiple
elements at once.
remove() and discard() are for deletion, but discard() is safer because it doesn’t throw errors
pop() is unique because it removes an element randomly, unlike the targeted remove() or
discard().
2. Explain the difference between shallow copy and deep copy with an example each
A shallow copy creates a new object but only copies references of the elements inside. If the
original object contains nested objects, changes in the nested objects will affect both the
original and the copy.
# let us see an example
import copy
original=[[1,2],[6,7]]
shallow=copy.copy(original)
shallow[0][1]=989
print(original,shallow,id(original),id(shallow),sep="\n")
A deep copy creates a new object and recursively copies all objects inside. Changes in nested
objects do not affect the original object.