Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

arrays

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

like image 747
alessandro Avatar asked Dec 10 '10 21:12

alessandro


People also ask

Does Python have index out of bounds?

Python list index out of range arises when we try to access an invalid index in our Python list. In Python, lists can be initialized without mentioning the length of the list. This feature allows the users to add as much data to the list without encountering errors.

What is the default value of index?

Answer. Answer: The Default Value is the value that a new record starts out with. You can change it if you want, but Access will create new records with this value.

How does Python handle index out of range?

“List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly.


1 Answers

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
like image 92
Martin v. Löwis Avatar answered Nov 12 '22 09:11

Martin v. Löwis