cooldood3490
cooldood3490

Reputation: 2488

List of List Class

I want to create my own List of Lists class. I want it to throw a list index out of range error when one of the indices are negative.

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

Example:

x = MyList([[1,2,3],[4,5,6],[7,8,9]])
x[-1][0]  # list index of of range -- Good
x[-1][-1] # list index out of range -- Good
x[0][-1]  # returns 3 -- Bad

How do I fix this? I've looked into possible solutions such as: Possible to use more than one argument on __getitem__?. But I can't get it to work.

Upvotes: 2

Views: 73

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

The outer list is a list of your custom class. However, each inner list is a list of the standard list class. Use the custom class for each list and it should work.

For example:

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

Upvotes: 6

Related Questions