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

Time:04-11

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

CodePudding user response:

you can do this by:-

list1 = ['a', 'b', 'c', 'd', 'e']
re_arrange_order = [-2, -1, 0, 1, 2]
for i in range(len(list1)):
    list1[i] = list1[re_arrange_order[i]]
print(list1)

CodePudding user response:

You can't change the index of a list. However, you can do it in other ways. For example

from collections import namedtuple

test = namedtuple("test", ["value", "index"])
v = [1, 2, 3, 4, 5]
result = []
start_index = -2
for i in v:
    result.append(test(value=i, index=start_index))
    start_index  = 1

print(result)
print(result[0].index)

Output

[test(value=1, index=-2), test(value=2, index=-1), test(value=3, index=0), test(value=4, index=1), test(value=5, index=2)]
-2

CodePudding user response:

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
  • Related