Skip to content Skip to sidebar Skip to footer

How To Extend List Class To Accept Lists For Indecies In Python, E.g. To Use List1[list2] = List3[list4]

I would like to extend the list class in Python so that it can accept lists of integers and booleans as indices. I am new to python and while I have some, albeit limited, experien

Solution 1:

Following the suggestion from @Tomerikoo in the comments, I am adding my last part here as an answer.

class MyList(list):

    def __getitem__(self, index):
        if type(index) is list:
            if type(index[0]) is bool:
                index = [i for i,v in enumerate(index) if v]
                return self[index]
            elif type(index[0]) is int:
                res = [None]*len(index)
                for i,v in enumerate(index):
                    res[i] = list.__getitem__(self, v)
                return res
        else:
            return list.__getitem__(self, index)

    def __setitem__(self, index, value):
        if type(index) is list:
            if type(index[0]) is bool:
                index = [i for i,v in enumerate(index) if v]
                self[index] = value
            elif type(index[0]) is int:
                for i,v in zip(index, value):
                    list.__setitem__(self,i,v)
        else:
            list.__setitem__(self,index,value)

There might be some issues with the above that I am not aware of, so will wait for other responses before accepting it. I suppose I should add some code that throws an error if index is neither int or bool.


Post a Comment for "How To Extend List Class To Accept Lists For Indecies In Python, E.g. To Use List1[list2] = List3[list4]"