Python Data structure index Start at 1 instead of 0?

49,296

Solution 1

Just insert a 0 at the beginning of the structure:

(0, 2, 4, 6, 8, ...)

Solution 2

You could override the item getter and make a specialized tuple:

class BaseOneTuple(tuple):
    __slots__ = () # Space optimization, see: http://stackoverflow.com/questions/472000/python-slots 
    def __new__(cls, *items):
        return tuple.__new__(cls, items) # Creates new instance of tuple
    def __getitem__(self, n):
        return tuple.__getitem__(self, n - 1)


b = BaseOneTuple(*range(2, 129, 2))
b[2] == 4

Solution 3

You could use a dictionary, or you could simply subtract one from your index before accessing it.

Also, I note that your 64 numbers are in a simple arithmetic progression. Why store them at all? You can use this:

def my_number(i):
    return 2*i

If the list you showed was actually an example, and the real numbers are more complicated, then use a list with a dummy first element:

my_nums = [0, 2, 4, 6, 8, ....]

Then you can get 2 as my_nums[1].

Solution 4

You could use range(2, 129, 2) to generate the numbers in the range 1 - 128 in increments of 2 and convert this list into a tuple if it's not going to change.

t = tuple(range(2, 129, 2))

def numbers(n):
   return t[n-1]

Given the global tuple t, function numbers could retrieve elements using a 1-based (instead of 0-based) index.

Share:
49,296
NASA Intern
Author by

NASA Intern

Updated on July 09, 2022

Comments

  • NASA Intern
    NASA Intern almost 2 years

    I have a weird question: I have this list of 64 numbers that will never change:

    (2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128)
    

    I need a data structure in Python that will allow me to accsess these numbers using a 1-64 index as opposed to the standard 0-63. Is this possible? Would the best way to accomplish this be to build a dictionary?

  • kay
    kay almost 12 years
    I think there is no other solution that will work well with 1-based slices.
  • NASA Intern
    NASA Intern almost 12 years
    No, those are the actual numbers.
  • NASA Intern
    NASA Intern almost 12 years
    Wow, can't believe it was that simple.. I was gonna use a dictionary.
  • NASA Intern
    NASA Intern almost 12 years
    Uhhhh, im not nearly good enough in Python yet to do this... thanks tho!
  • yantrab
    yantrab almost 12 years
    Why would you store the numbers from 2 to 128? Just double your index, and you have the number...
  • NASA Intern
    NASA Intern almost 12 years
    Well, these numbers are ID's from canvas objects. I cant find away to change them. It's rather complicated
  • BHS
    BHS over 6 years
    Length of the array can't be used as is in this approach. Hashmap would fix this but might be a overkill :)