Redefining python list – Education Career Blog

is it possible to redefine the behavior of a Python List from Python, I mean, without having to write anything in the Python sourcecode?

,

You could always create your own subclass inheriting from list.

An example (although you would probably never want to use this):

class new_list(list):
    '''A list that will return -1 for non-existent items.'''
    def __getitem__(self, i):
        if i >= len(self):
            return -1
        else:
            return super(new_list, self).__getitem__(i)

l = new_list(1,2,3)
l2 #returns 3 just like a normal list
l3 #returns -1 instead of raising IndexError

Leave a Comment