user8203141
user8203141

Reputation:

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

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

Answers (2)

Carter
Carter

Reputation: 439

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

Upvotes: 10

Daniel
Daniel

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

Related Questions