Python: Accessing Values in a Set

In Sets we can not access set items by referring to its index because set is unordered the items has no index. We can not access single elements in set but, we can access all elements using for loop or ask if a specified value is present in a set, by using the in keyword.

Access All Set Elements

fruits = set(['apple','banana','cherry','pineapple'])
for i in fruits:
    print(i)

Output:

banana
apple
pineapple
cherry

Verify item is present in Set

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

Output: True

Tags