Skip to content
Advertisement

Is there any way we can change the index location of an element present in a list?

Example:- list1 = [ a, b, c, d, e] has index location 0, 1, 2, 3, 4 Can we make the index locations for list1 -2, -1, 0, 1, 2

Advertisement

Answer

Lists are only indexable via positive integers (negatives have a special behavior to begin looking from the back of the list) and have a contiguous range up to the size of the list.

If you want to index by other means, either use a dictionary, or create a helper method to do this translation for you. Alternatively you could subclass the list (but this is the most complex and has a lot of corner cases to consider):

Dictionary solution.

list1 = ['a', 'b', 'c', 'd', 'e']
list1 = {i - 2: v for i, v in enumerate(list1)} 
print(list1[-2])
a

Helper method solution:

def fetch_val(data, i):
    return data[i + 2]

fetch_val(['a', 'b', 'c', 'd', 'e'], -2)
a

Override the list class:

class SpecialList(list):
    def __init__(self, start, *args, **kwargs):
        self.start = start
        super().__init__(*args, **kwargs)

    def __getitem__(self, item):
        return super().__getitem__(item - self.start)

    def __setitem__(self, key, value):
        super().__setitem__(key - self.start, value)


list1 = SpecialList(-2, ['a', 'b', 'c', 'd', 'e'])
print(list1[-2])
a
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement