how to index a set in python code example
Example: how to index a set in python
"""
You can't index a set in python.
The concept of sets in Python is inspired in Mathmatics. If you are interested
in knowing if any given item belongs in a set, it shouldn't matter "where" in
the set that item is located. With that being said, if you still want to
accomplish this, this code should work, and, simultaneously, show why it's a
bad idea
"""
def get_set_element_from_index (input_set : set, target_index : int):
if target_index < 0:
target_index = len(input_set) + target_index
index = 0
for element in input_set:
if index == target_index:
return element
index += 1
raise IndexError ('set index out of range')
my_set = {'one','two','three','four','five','six'}
print (my_set)
print(get_set_element_from_index(my_set, 0))
print(get_set_element_from_index(my_set, 3))
print(get_set_element_from_index(my_set, -1))
print(get_set_element_from_index(my_set, 6))