How to Access Items in a Python Set
Learn how to work with Python sets by accessing items. Discover that sets do not support indexing or key-based access, but you can loop through items using a for loop or check for item presence using the in
keyword.
Python - Access Set Items
Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in
keyword.
Example
thisset = {"orange", "grape", "mango"}
for x in thisset:
print(x)
Output
orange
grape
mango
Example
Check if "grape" is present in the set:
Example
thisset = {"orange", "grape", "mango"}
print("grape" in thisset)
Output
True
Example
Check if "banana" is NOT present in the set:
Example
thisset = {"orange", "grape", "mango"}
print("banana" not in thisset)
Output
True
Change Items
Once a set is created, you cannot change its items, but you can add new items.