Sets Flashcards
Definition of a set
A set is a unique collection of objects in Python. You can denote a set with a curly bracket {}. Python will automatically remove duplicate items:
Convert list to set will remove duplicate items
album_list = [“Michael Jackson”, “Thriller”, 1982, “00:42:19”, \
“Pop, Rock, R&B”, 46.0, 65, “30-Nov-82”, None, 10.0]
album_set = set(album_list)
album_set
Add an element using add()
A.add(“NSYNC”)
A
{‘AC/DC’, ‘Back in Black’, ‘NSYNC’, ‘Thriller’}
Remove an element
A.remove(“NSYNC”)
A
We can verify if an element is in the set using the in command:
“AC/DC” in A
True
Find intersection of 2 sets
You can find the intersect of two sets as follow using &:
intersection = album_set1 & album_set2
intersection
{‘AC/DC’, ‘Back in Black’}
You can find all the elements that are only contained in album_set1 using the difference method:
album_set1.difference(album_set2)
{‘Thriller’}
The elements in album_set2 but not in album_set1 is given by:
album_set2.difference(album_set1)
{‘The Dark Side of the Moon’}
Union of 2 albums
album_set1.union(album_set2)
{‘AC/DC’, ‘Back in Black’, ‘The Dark Side of the Moon’, ‘Thriller’}
And you can check if a set is a superset or subset of another set, respectively, like this:
set(album_set1).issuperset(album_set2)
False