SET Different Methods With Examples
Rushikesh J.
Software Test Engineer @Vinz Global | Robot Framework | Manual Testing, Automation Testing | Python | Selenium | GIT | JIRA | Immediate Joiner | API Testing Using Postman | Jenkins
SET Method : add()
Working: This method is used to add element to set.
Syntax:
set.add(“pink")
Example:
color = {“gray”, ”red”, ”white”}
color.add(“pink")
print(color)
Result:
{“gray”, ”red”, ”white”, ”pink”}
SET Method : clear()
Working: It used to remove all the elements from a set
Syntax:
set.clear()
Example:
color = {“gray”, ”red”, ”white”}
color.clear()
print(color)
Result:
{}
SET Method : copy()
Working: It used to copy the set + its elements.
Syntax:
new_set = set.copy()
Example:
color = {“gray”, ”red”, ”white”}
new_color? = color.copy()
print(new_color)
Result:
{“gray”, ”red”, ”white”}
SET Method : discard()
Working: It used to remove specific element from a set.
Syntax:
set.discard()
Example:
color = {“gray”, ”red”, ”white”}
color.discard(“red”)
print(color)
Result:
{“gray”, ”white”}
SET Method : isdisjoint()
Working: It will return True if all the elements of A set are absent in Other B set. Otherwise it return false. Disjoint means there are no relation of A set with B set in any way.
Syntax:
set1.isdisjoint(set2)
Example:
A = {3, 1, 0, 6}
B = {2, 7, -4}
print(A.isdisjoint(B))
Result:
True
SET Method : issubset()
Working: It returns True if ALL items / elements of A set, present in B set, otherwise it return False
Syntax:
setA.issubset(setB)
Example:
A = {3, 1, 0, 6}
B = {2, 7, -4, 3,0,10,8,6,1}
print(A.issubset(B))
print(B.issubset(A))
Result:
True
False
SET Method : issuperset()
Working: When A set is the subset of B set, then B set will be superset of A set. It is opposite to sub set concept.
Syntax:
setB.issuperset(setA)
Example:
A = {5, 2, 4, 6}
B = {7, 1, 5, 2, 6, 9, 4, 12}
print(A.issubset(B)) # True
print(B.issuperset(A)) # True
Result:
True
True
SET Method : pop()
Working: This method is used to remove top element from a set. And it return removed element
Syntax:
set.pop()
Example:
A = {7, 1, 5, 2, 6, 9, 4, 12}
print(A.pop())
Result:
#it will return remove element, as it display random items, it may display any number
SET Method : remove()
Working: This method is used to remove any specific element from a set. It different from discard method, because remove method raise error, if element no exist, while discard method did not.
Syntax:
set.remove(element)
Example:
A = {7, 1, 5, 2, 6, 9, 4, 12}
A.remove(12)
print(A)
Result:
{7, 1, 5, 2, 6, 9, 4}
SET Method : update()
Working: This method is used to update a set. Update method take argument, that may be any list, tuple, dictionary or set. It convert different data type to set and add? elements to set to update
Syntax:
set.update(set or list or tuple or dictionary)
Example:
A = {7, 1, 5, 2, 6, 9, 4, 12}
B = {11,13,14,15}
A.update(B)
print(A)
Result:
{7, 1, 5, 2, 6, 9, 4, 11, 13, 14, 15}