how to index a set in python

Solutions on MaxInterview for how to index a set in python by the best coders in the world

showing results for - "how to index a set in python"
Mika
05 Feb 2019
1"""
2You can't index a set in python.
3The concept of sets in Python is inspired in Mathmatics. If you are interested
4in knowing if any given item belongs in a set, it shouldn't matter "where" in
5the set that item is located. With that being said, if you still want to
6accomplish this, this code should work, and, simultaneously, show why it's a 
7bad idea
8"""
9
10def get_set_element_from_index (input_set : set, target_index : int):
11    if target_index < 0:
12        target_index = len(input_set) + target_index
13    index = 0
14    for element in input_set:
15        if index == target_index:
16            return element
17        index += 1
18    raise IndexError ('set index out of range')
19
20my_set = {'one','two','three','four','five','six'}
21print (my_set) # unpredictable output. Changes everytime you run the script
22# let's say the previous print nails the order of the set (same as declared)
23print(get_set_element_from_index(my_set, 0))  # prints 'one'
24print(get_set_element_from_index(my_set, 3))  # prints 'four'
25print(get_set_element_from_index(my_set, -1)) # prints 'six'
26print(get_set_element_from_index(my_set, 6))  # raises IndexError