- Home
- Course Detail
regularpython@gmail.com
You are now watching:
Python Sets / of Python Set In-Built Functions
#remove():Removes Element from the Set #Syntax : set.remove(element) student = {"Ram", 200, 205.04} student.remove("Ram") print(student)
# add():adds element to a set student = {"Ram", 200, 205.04} student.add("Krish") print(student)
# copy():Returns Shallow Copy of a Set numbers = {1, 2, 3, 4} new_numbers = numbers.copy() print(new_numbers)
# clear():remove all elements from a set student = {"Ram", 200, 205.04} student.clear() print(student)
# difference():Returns Difference of Two Sets marks1 = {100,102,500} marks2 = {100,200,300,500} print(marks1.difference(marks2)) print(marks2.difference(marks1)) #other way print(marks1-marks2) # print(marks2-marks1)
# # intersection():Returns Intersection of Two or More Sets A = {1, 2, 3, 4} B = {5, 2, 1, 6, 4} C = {2, 3, 5, 6, 4} print(B.intersection(A)) print(B.intersection(C)) print(A.intersection(C)) print(C.intersection(A, B)) print(A & C) print(A & B) print(A & C & B) print(A & B & C)
# intersection_update():Updates Calling Set With Intersection of Sets data = [[1,2,3,4], [8,7,3,2], [9,2,6], [5,1,3]] A = set(data[0]) print(A) for currentSet in data[1:]: A.intersection_update(currentSet) print(A) print("final result = ",A)
# difference_update():Updates Calling Set With Intersection of Sets A = {'a', 'c', 'g', 'd'} B = {'c', 'f', 'g'} # A.difference_update(B) # print('A = ', A) print('B = ', B)
# discard():Removes an Element from The Set numbers = {1, 2, 3, 4, 5, 6} # Returns None # Meaning, absence of a return value print(numbers.discard(3)) print('numbers =', numbers)
# isdisjoint():Checks Disjoint Sets A = {1, 2, 3,4} B = {8, 5, 6} C = {7,2, 8, 9} print('Are A and B disjoint?', A.isdisjoint(B)) print('Are A and C disjoint?', A.isdisjoint(C))
# issubset():Checks if a Set is Subset of Another Set A = {1, 2, 3, 4, 5, 6, 7} B = {1,4,9} # Returns True print(B.issubset(A))
# pop():Removes an Arbitrary Element A ={'a', 'b', 'c', 'd'} print('Return Value is', A.pop()) print('A = ', A)
# symmetric_difference():Returns Symmetric Difference A = {1, 2, 4, 6} B = {3, 4, 5, 6,7} C = {} re = A.symmetric_difference(B) print(re) print(B.symmetric_difference(A)) print(A.symmetric_difference(C)) print(B.symmetric_difference(C))
# symmetric_difference_update():Updates Set With Symmetric Difference A = {1, 2, 4, 6} B = {3, 4, 5, 6,7} result = A.symmetric_difference_update(B) print('A = ', A) print('B = ', B) print('result = ', result)
# union():Returns Union of Sets A = {'a', 'c', 'd'} B = {'c', 'd', 2 } C= {1, 2, 3} print('A U B =', A.union(B)) print('B U C =', B.union(C)) print('A U B U C =', A.union(B, C)) # print('A.union() = ', A.union()) # # update() A = {1, 2, 3, 4} B = {5, 6, 3, 8} # B.update(A) print('A =',A) print('B =',B)