Access Set Items
Cannot Access by Index
Sets are unordered collections, so their elements do not have a fixed position. This means you cannot use indexing or slicing like you would with lists or tuples.
To work with sets safely, you can check if an element exists using the 'in' keyword.
Example
# Checking if item exists
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)
print("orange" in fruits)
Output
True False
Iterating Through Sets
Although sets do not support indexing, you can iterate through all elements using a for loop. The order of items when iterating is not guaranteed and may change.
Example
# Looping through a set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
Output
apple banana cherry