Hi, what's a more pythonic way to set a value in python for any index in a list?

I am creating my own data structure in python which I call array. One property I would like this to be if, for example, array = [1,2]

it is possible to write array[5] = 6

and then array = [1,2,None,None,None,6]

. I did it, 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

      

+3


source to share


2 answers


def __setitem__(self, index, value):
    self.array += [None] * (index + 1 - len(self))
    self.array[index] = value

      



+10


source


This looks quite normal to me. An exception is an element outside the existing range, but using the try-except method is correct. You should also consider the case where it is index

not more than the 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)

      

0


source







All Articles