if you do not want to overwrite the getimtem of lists you can write a get method like dict have:
class fancyList_if(list):
def get(self, index, default = None):
if (index > len(self)):
return default
return self.__getitem__(index)
if you rarely expect to get out of bounds then you can implement this as an exce
class fancyList_except(list):
def get(self, index, default = None):
try:
self.__getitem__(index)
except IndexError:
return default
benshmarks:
In [58]: a = fancyList_if((1,3,4,5))
In [59]: b = fancyList_except((1,3,4,5))
In [60]: %timeit a.get(2, 10)
1000000 loops, best of 3: 494 ns per loop
In [61]: %timeit a.get(10, 10)
1000000 loops, best of 3: 305 ns per loop
In [62]: %timeit b.get(2, 10)
1000000 loops, best of 3: 409 ns per loop
In [63]: %timeit b.get(10, 10)
1000000 loops, best of 3: 1.67 us per loop
break even:
500hit + 300miss = 400hit + 1700miss
hit/miss = 14
so if you expect more than 1 in 14 look up 'fails' then use the if statement else use the try/catch.