Welcome to our deep dive into Python's Set Methods! In this comprehensive guide, we'll explore various methods that let you manipulate sets in Python. By the end of this tutorial, you'll be equipped with the skills needed to work with sets like a pro! 💡
A set is a collection of unique elements, enclosed within curly braces {} or defined using the set() constructor. Sets are unordered, and elements do not have a defined order.
my_set1 = {1, 2, 3, 4, 5}
my_set2 = set([6, 7, 8, 4, 9])The add() method adds a single element to the set.
my_set1.add(6)
print(my_set1) # {1, 2, 3, 4, 5, 6}The remove() method removes a specific element from the set.
my_set1.remove(4)
print(my_set1) # {1, 2, 3, 5, 6}If the element does not exist in the set, a KeyError will be raised.
The discard() method works just like remove(), but it doesn't raise an error if the element doesn't exist in the set.
my_set1.discard(10)
print(my_set1) # {2, 3, 5, 6}The pop() method randomly selects and removes an element from the set.
my_set1.pop() # Removes and returns 2, 3, 5, or 6
print(my_set1) # {5, 6}The clear() method removes all elements from the set.
my_set1.clear()
print(my_set1) # set()The update() method adds elements from another set to the current set.
my_set1 = {5, 6}
my_set2 = {7, 8, 9}
my_set1.update(my_set2)
print(my_set1) # {5, 6, 7, 8, 9}The intersection() method returns a new set containing elements common to both sets.
my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}
print(my_set1.intersection(my_set2)) # {4, 5}The union() method returns a new set containing elements from both sets.
my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}
print(my_set1.union(my_set2)) # {1, 2, 3, 4, 5, 6, 7, 8}The difference() method returns a new set containing elements from the current set but not from the other set.
my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}
print(my_set1.difference(my_set2)) # {1, 2, 3}The symmetric_difference() method returns a new set containing elements that are in either of the two sets but not in both.
my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}
print(my_set1.symmetric_difference(my_set2)) # {1, 2, 3, 6, 7, 8}The issubset() method checks if all elements of the current set are present in the other set. It returns True if the current set is a subset of the other set, and False otherwise.
my_set1 = {1, 2, 3}
my_set2 = {1, 2, 3, 4, 5}
print(my_set1.issubset(my_set2)) # TrueThe issuperset() method checks if all elements of the other set are present in the current set. It returns True if the current set is a superset of the other set, and False otherwise.
my_set1 = {1, 2, 3, 4, 5}
my_set2 = {1, 2, 3}
print(my_set1.issuperset(my_set2)) # TrueWhich method adds a single element to a set?
That's all for our Python Tutorial: Set Methods! With this knowledge, you can now efficiently manage sets and their elements with ease. Happy coding! 💡