Accessing Set Items
Since sets are unordered, you cannot access items using indices. However, you can loop through the set items using a for
loop or check if an item exists using the in
keyword.
Looping Through a Set
Example: Iterating Over a Set
# Looping through a set
fruits = {"Apple", "Banana", "Cherry"}
for fruit in fruits:
print("Fruit:", fruit)
Output (Order may vary)
Fruit: Cherry
Fruit: Banana
Fruit: Apple
Checking for Item Existence
Example: Using in
Keyword
# Checking if an item exists in a set
names = {"Karthick AG", "Durai", "Vijay"}
print("Durai" in names) # True
print("Praveen" in names) # False
Output
True
False
Explanation: Since sets are unordered, you cannot access items by index. Instead, you can loop through the set or use the in
keyword to check for the existence of an item.