Sets, explained simply
A set is a collection where every item appears only once. If you add something that is already there, nothing changes. That makes sets perfect for removing duplicates.
You can turn a list into a set with set(my_list). Sets do not keep items in order, so you cannot use an index with them.
Sets are great for questions like "is this in the group?" using in, and for comparing groups: & finds items in both, | combines them.
Example: Find the unique gems
found = ["ruby", "opal", "ruby", "jade", "opal"]
unique = set(found)
print(len(found), "found,", len(unique), "different")
print("jade" in unique)Output
5 found, 3 different
TrueTry this
- Find the different letters in the word "banana".
- Make two sets of hobbies and print the ones you and a friend share using &.
- Add an item twice with .add() and check the length.
