In this chapter, let us look at the Python set object which is used to store multiple items just as tuples, lists, and dictionaries.
You can declare a set object with one of these methods:-
set1 = {1,2,3} set2 = set((1,2,3))
In order to remove an element from a set, use the remove or discard method as follows:-
set1.remove(2) # {1,3} set1.discard(3) # {1}
In order to remove the front element from a set, use the pop method.
set1.pop() # {2,3}
Insert an element to the end of the set with the add method.
set1.add(5) #{1,2,3,5}
Find the difference between two set elements:-
set1 = {1,2,3} set2 = set((1,4,6)) set3 = set1.difference(set2) # {2,3}
As you can see this method will subtract the element within two sets based on their index position.
Clear all the elements within a set:-
set1.clear()
Find the common elements within two sets:-
set1 = {1,2,3} set2 = set((1,4,6)) set3 = set1.intersection(set2) # {1}
Combined all the elements within two sets:-
set1 = {1,2,3} set2 = set((1,4,6)) set3 = set1.union(set2) # {1,2,3,4,6}
Copy a set of elements into another set:-
set3 = set1.copy() # {1, 2, 3}
Find out whether a set is a subset of another set:-
set1 = {1,2,3} set2 = set((1,4,6)) set1.issubset(set2) # False
There are still lots of methods that you can read on the official documentation page of Python regarding the set object!
Thanks for the article. However, I think you should check again what difference() does. It does not subtract individual members from each other. Otherwise, you would end up with the result {0, 2, 3}.
In fact, it simply returns a set that contains items that only exist in set1, and not in set2.
JL