Reputation:
I am creating my own data structure in python which I call an Array. One property that I would like it to have is if for instance array = [1,2]
, one could write array[5] = 6
and then array = [1,2,None,None,None,6]
. I have accomplished this, but my code seems very awkward.
def __setitem__(self,index,value):
try:
self.array[index] = value
except IndexError:
if index+1 > len(self):
add = index + 1 - len(self)
self.array += [None] * add
self.array[i] = value
Upvotes: 3
Views: 114
Reputation: 439
def __setitem__(self, index, value):
self.array += [None] * (index + 1 - len(self.array))
self.array[index] = value
Upvotes: 10
Reputation: 42768
This looks quite ok to me. If setting an element outside the existing range is an exception, using try-except here is the correct way. You should also consider the case, where index
is not larger than length of the list.
from itertools import repeat
def __setitem__(self,index,value):
try:
self.array[index] = value
except IndexError:
if index < 0:
raise
self.array.extend(repeat(None, index-len(self)))
self.array.append(value)
Upvotes: 0