Skip to main content

Sets

Sets​

  • unlike lists and tuples, sets are unordered (do not record element position)
music_genres_1 = {'ballad', 'bop', 'rock', 'bop', 'RnB', 'disco'}
print(music_genres_1)
# -> duplicate items will not be present in Sets
Output
{'RnB', 'disco', 'bop', 'rock', 'ballad'}

1/ set()​

list1 = ['kevinph4n', 'is', 'handsome', 'handsome', 2008]
list1_set = set(list1)
print(list1_set)
Output
{2008, 'is', 'kevinph4n', 'handsome'}

2/ .add()​

A = {"thriller", "ballad", "rnb"}
A.add("kevin")
print(A)
Output
{'rnb', 'thriller', 'kevin', 'ballad'}
A = {"thriller", "ballad", "rnb"}
A.add("kevin")
print("kevin" in A)
Output
True

3/ Sets Mathematical Set Operations​

# &
album_set1 = {"X", "French Exit", "HVL"}
album_set2 = {"X", "French Exit", "Loi Choi"}
album_set_similar = album_set1 & album_set2
print(album_set_similar)
Output
{'X', 'French Exit'}
# .union()
album_set1 = {"X", "French Exit", "HVL"}
album_set2 = {"X", "French Exit", "Loi Choi"}
album_set_union = album_set1.union(album_set2)
print(album_set_union)
Output
{'French Exit', 'HVL', 'Loi Choi', 'X'}
# .issubset()
album_set1 = {"X", "French Exit"}
album_set2 = {"X", "French Exit", "HVL"}
print(album_set1.issubset(album_set2))
Output
True
note

Sets are unordered, so the printed order can be different on your machine.