Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a __getitem__ method that allows list[][] indexing (2D)

I am trying to make a getitem method where I can use [][] to get an element from and array I have made. The method I came across is this:

def __getitem__(self, item):
        x, y = item 
        return self.twoDim[x][y]

The problem with this is that I only can access the array by using a tuple, like array[1,0]. What I want is to be able to do this: array[1][0].

Im not sure how to pass these two arguments inside the getitem method since it only can take one at a time.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any tips on how to make it work? Thank you 🙂

>Solution :

In Python, two pairs of square brackets mean twice indexes, so array[1][0] is equivalent to:

array.__getitem__(1).__getitem__(0)

After one index, your twoDim can return the object that can be indexed again, so if the index has only one element, you can apply it to twoDim directly:

def __getitem__(self, item):
    if not isinstance(item, tuple):
        return self.twoDim[item]
    x, y = item
    return self.twoDim[x][y]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading