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.

classMyList(list):

    def__getitem__(self, index):
        iftype(index) islist:
            iftype(index[0]) isbool:
                index = [i for i,v inenumerate(index) if v]
                return self[index]
            eliftype(index[0]) isint:
                res = [None]*len(index)
                for i,v inenumerate(index):
                    res[i] = list.__getitem__(self, v)
                return res
        else:
            returnlist.__getitem__(self, index)

    def__setitem__(self, index, value):
        iftype(index) islist:
            iftype(index[0]) isbool:
                index = [i for i,v inenumerate(index) if v]
                self[index] = value
            eliftype(index[0]) isint:
                for i,v inzip(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]"