Lesson 21 of 4053%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Sets
Store unordered, unique items.
Sets
What You’ll Learn
You’ll learn how to use sets to store unique items.
What is a Set?
A set is a collection which is unordered, unchangeable (though you can add/remove items), and unindexed. Sets are written with curly brackets {}.
Sets cannot have two items with the same value.
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)
Expected Output:
{'banana', 'cherry', 'apple'}
(Notice the duplicate ‘apple’ was ignored, and the order might change!)
Accessing Items
Since sets are unordered, they don’t have indexes. You cannot do fruits[0]. You must loop through them or check if an item exists using in.
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits) # True
Adding and Removing
fruits.add("orange")
fruits.remove("apple")