Python Core



Admission Enquiry Form


Sets methods in python

Python has in-built methods for sets.

 

add() method in sets

The add() method adds an element to the set.

courses={"Python","C","C++"}
print(courses)
courses.add("Java")
print(courses)



Output

{'Python', 'C++', 'C'}
{'Java', 'Python', 'C++', 'C'}



intersection() method in sets

The intersection() method returns a set that contains the similarity between two or more sets.

courses1={"Python","C","C++"}
courses2={"Java","Python","HTML"}
courses3=courses1.intersection(courses2)
print(courses3)



Output

{'Python'}



Another example of intersection() method in sets

courses1={"Python","C","C++"}
courses2={"Java","Python","HTML"}
courses3={"CSS","sjQUERY","Python"}
courses4=courses1.intersection(courses2,courses3)
print(courses4)


Output

{'Python'}



union() method in sets

The union() method returns a set that contains all items from the original set, and all items from the specified set(s).

courses1={"Python","C","HTML"}
courses2={"Java","Python","HTML"}
courses3=courses1.union(courses2)
print(courses3)


Output

{'C', 'HTML', 'Java', 'Python'}



pop() method in sets

The pop() method removes a random element from the set.

courses1={"Python","C","HTML"}
courses1.pop()
print(courses1)


Output

{'C', 'HTML'}



remove() method in sets

The remove() method removes the specified element from the set..

courses1={"Python","C","HTML"}
courses1.remove("C")
print(courses1)


Output

{'Python', 'HTML'}



discard() method in sets

The discard() method removes the specified element from the set.

This method is different from the remove() method, because the remove() method will raise an error if the specified element does not exist, and the discard() method will not.

courses1={"Python","C","HTML"}
courses1.discard("HTML")
print(courses1)


Output

{'Python', 'C'}



symmetric_difference() method in sets

The symmetric_difference() method returns a set that contains all items from both set, but not the items that are present in both sets.

courses1={"Python","C","C++"}
courses2={"Java","Python","HTML"}
courses3=courses1.symmetric_difference(courses2)
print(courses3)


Output

{'HTML', 'C', 'C++', 'Java'}






copy() method in sets

The copy() method returns a copy of the specified set..

courses={"PYTHON","HTML","Web Designing"}
cpy=courses.copy()
print(cpy)


Output

{'PYTHON', 'Web Designing', 'HTML'}






clear() method in set

The clear() method removes all the elements from a set.

courses={"PYTHON","HTML","Web Designing"}
courses.clear()
print(courses)


Output

set()