11

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?

NASA Intern
  • 823
  • 3
  • 11
  • 19

4 Answers4

41

Just insert a 0 at the beginning of the structure:

(0, 2, 4, 6, 8, ...)
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
6

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
jamylak
  • 128,818
  • 30
  • 231
  • 230
Kijewski
  • 25,517
  • 12
  • 101
  • 143
4

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].

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
3

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.

Levon
  • 138,105
  • 33
  • 200
  • 191