Answers for "how to get set at index python"

1

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) # unpredictable output. Changes everytime you run the script
# let's say the previous print nails the order of the set (same as declared)
print(get_set_element_from_index(my_set, 0))  # prints 'one'
print(get_set_element_from_index(my_set, 3))  # prints 'four'
print(get_set_element_from_index(my_set, -1)) # prints 'six'
print(get_set_element_from_index(my_set, 6))  # raises IndexError
Posted by: Guest on June-02-2021

Python Answers by Framework

Browse Popular Code Answers by Language