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.

JavaScript
JavaScript

Helper method solution:

JavaScript
JavaScript

Override the list class:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement