alessandro
alessandro

Reputation: 3984

python: array default value for index out-of-bounds

I need a good way to ask for an array/matrix value, but reporting a default (0) value for out-of-bound index:
b[2][4] should return 0 if the 2nd index length is 3, and
b[-1][2] also
I checked this: Getting a default value on index out of range in Python, but it seems to me that it would not work for negative indices - since python always add the array length to them (true?)
I was thinking along the line of overloading __getitem__, but I just came to python 1 month ago, and I'm not so skilled...

any help appreciated!

alessandro

Upvotes: 7

Views: 8168

Answers (4)

RoeeK
RoeeK

Reputation: 1162

for general knowledge, the usage of getitem and setitem is this:

(inside object class)

def __getitem__(self,index):
    print index
    return self.mylist[index]

def __setitem__(self,index,value):
    self.mylist[index]=value

if you override the list class ( class newListClass(list): ), and want to use the getitem of the list inside your own getitem, you need to write:

class newListClass(list):
    def __getitem__(self,index):
        return list.__getitem__(self,index)

this way you can also catch exception from this getitem and return what you want instead. that's not an answer for your problem, Martin's is.. but you interested in the getitem usage, so thats the way to do it. enjoy :)

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61557

since python always add the array length to them (true?)

The built-in Python sequences do this, but as far as I can tell it's done by those sequences' implementations, not by the Python compiler. So no, you'll receive negative values in your __getitem__ (or __getslice__) and can handle them as you wish.

Upvotes: 0

Martin v. Löwis
Martin v. Löwis

Reputation: 127477

If you want a indefinitely-sized sparse matrix, you can use defautldict:

py> matrix=defaultdict(lambda:defaultdict(lambda:0))
py> matrix[2][4]
0
py> matrix[2][4]=8
py> matrix[2][4]
8
py> matrix[-1][2]
0

Upvotes: 8

nate c
nate c

Reputation: 9005

I think your confusing the issue.

listy[-1] is a relative index such that, the true index equals len(listy),

listy[-2] true index is len(listy) -1, ... and so on

If the relative index does not exist it will still raise an IndexError. Such as this: [][0] or this [1][-2]

Upvotes: 0

Related Questions