Access Set Items
What You'll Learn: In this tutorial, you'll discover how to access items in a set. Unlike lists or tuples, sets do not support indexing, but there are ways to work with the items in a set.
Loop Through a Set
You cannot access items in a set by referring to an index or a key. However, you can loop through the set items using a for loop.
Example Code:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
apple
banana
cherryWhat's Happening Here?
- The for loop goes through each item in
thissetand prints it.
Check if an Item is Present
You can check if a specified value is present in a set using the in keyword.
Example Code:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
Output: True
What's Happening Here?
print("banana" in thisset)checks if 'banana' is inthissetand printsTrue.
Check if an Item is Not Present
You can also check if a specified value is not present in a set using the not in keyword.
Example Code:
thisset = {"apple", "banana", "cherry"}
print("banana" not in thisset)
Output: False
What's Happening Here?
print("banana" not in thisset)checks if 'banana' is not inthissetand printsFalse.
Change Items
Once a set is created, you cannot change its items directly, but you can add new items to the set.
Try It Yourself: Fun Exercises
- Loop Through Your Favorite Fruits:
- Create a set of your favorite fruits.
- Use a for loop to print each fruit.
- Check for a Fruit:
- Write a set of fruits.
- Use the
inkeyword to check if a specific fruit is in the set.
Summary:
In this Python tutorial, we learned how to access items in a set using loops and the in keyword. Unlike lists or tuples, sets do not support indexing, but you can still work with set items effectively. Keep experimenting and have fun with sets in Python!