2.0 Python: Access Set Items
2.1 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.
2.1.1 Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
2.1.2 Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
if 'banana' in thisset:
print('"banana" in thisset')
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
thisset = {"apple", "banana", "cherry"}
print(f'Is "banana" in thisset? {"banana" in thisset}')
2.1.3 Example
Check if "banana" is NOT present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" not in thisset)
note
Once a set is created, you cannot change its items, but you can add new items.