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.
JavaScript
x
4
1
list1 = ['a', 'b', 'c', 'd', 'e']
2
list1 = {i - 2: v for i, v in enumerate(list1)}
3
print(list1[-2])
4
JavaScript
1
2
1
a
2
Helper method solution:
JavaScript
1
5
1
def fetch_val(data, i):
2
return data[i + 2]
3
4
fetch_val(['a', 'b', 'c', 'd', 'e'], -2)
5
JavaScript
1
2
1
a
2
Override the list class:
JavaScript
1
15
15
1
class SpecialList(list):
2
def __init__(self, start, *args, **kwargs):
3
self.start = start
4
super().__init__(*args, **kwargs)
5
6
def __getitem__(self, item):
7
return super().__getitem__(item - self.start)
8
9
def __setitem__(self, key, value):
10
super().__setitem__(key - self.start, value)
11
12
13
list1 = SpecialList(-2, ['a', 'b', 'c', 'd', 'e'])
14
print(list1[-2])
15
JavaScript
1
2
1
a
2