Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Force List Index out of Range Exception

Tags:

python

list

I have a list of lists

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I want the code to throw an Array Out of Bounds Exception similar to how is does in Java when the index is out of range. For example,

x[0][0]   # 1
x[0][1]   # 2
x[0-1][0-1]  # <--- this returns 9 but I want it to throw an exception
x[0-1][1]    # <--- this returns 7 but again I want it to throw an exception
x[0][2]     # this throws an index out of range exception, as it should

If an exception is thrown, I want it to return 0.

try:
    x[0-1][0-1]   # I want this to throw an exception
except:
    print 0       # prints the integer 0

I think basically anytime the index is negative, throw an exception.

like image 920
cooldood3490 Avatar asked Apr 17 '15 22:04

cooldood3490


People also ask

How do I fix list index out of range in Python?

The Python IndexError: list index out of range can be fixed by making sure any elements accessed in a list are within the index range of the list. This can be done by using the range() function along with the len() function.

How do you fix a list index out of range in a for loop?

To fix this, you can modify the parameter in the range() function. A better solution is to use the length of the list as the range() function's parameter. The code above runs without any error because the len() function returns 3. Using that with range(3) returns 0, 1, 2 which matches the number of items in a list.

Is list index out of range a runtime error?

In this tutorial, you'll learn how all about the Python list index out of range error, including what it is, why it occurs, and how to resolve it. The IndexError is one of the most common Python runtime errors that you'll encounter in your programming journey.

How do I stop list assignment index out of range?

The “indexerror: list assignment index out of range” is raised when you try to assign an item to an index position that does not exist. To solve this error, you can use append() to add an item to a list. You can also initialize a list before you start inserting values to avoid this error.


2 Answers

You can create your own list class, inheriting the default one, and implementing the __getitem__ method that returns the element in a specified index:

class MyList(list):
    def __getitem__(self, index):
        if index < 0:
            raise IndexError("list index out of range")
        return super(MyList, self).__getitem__(index)

Example:

>>> l = MyList([1, 2, 3])
>>> l[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __getitem__
IndexError: list index out of range
>>> l[0]
1
>>> l[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __getitem__
IndexError: list index out of range
like image 126
JuniorCompressor Avatar answered Sep 17 '22 21:09

JuniorCompressor


There is a better way to handle the border cases: just increase the array by two in both dimensions and fill all border with a default (e.g. 0) and never update them. For neighbourhood and update, just search the inner field (index 1..(len-2)), instead of 0..len-1. So, the indexes will never be out of bounds for the neighbourhood search. This elliminates the need for special treatment. (I did this many years ago for the same usage, but in a different language - Pascal, iirc.)

like image 20
too honest for this site Avatar answered Sep 18 '22 21:09

too honest for this site