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:

python
thisset = {"apple", "banana", "cherry"}
for x in thisset:
    print(x)

Output:

apple
banana
cherry

What's Happening Here?

  • The for loop goes through each item in thisset and 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:

python
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

Output: True
 

What's Happening Here?

  • print("banana" in thisset) checks if 'banana' is in thisset and prints True.

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:

python
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 in thisset and prints False.

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

  1. Loop Through Your Favorite Fruits:
    • Create a set of your favorite fruits.
    • Use a for loop to print each fruit.
  2. Check for a Fruit:
    • Write a set of fruits.
    • Use the in keyword 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!