[Python] Wrong indexing of a user defined list [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Python class inheriting from Sequence. I implemented __getitem__ and __len__ in a straightforward way. In the main I loop over the elements of the class initialized with a list of two strings:

    class MyList(Sequence):
    def __init__(self, asset_list):
    self.L = asset_list
    super().__init__()

    def __getitem__(self, indexer):
    if isinstance(indexer, int):
    return self.L[indexer]
    else:
    raise Exception

    def __len__(self):
    return len(self.L)

    if __name__ == "__main__":
    al = MyList(["hello", "world"])
    for x in al:
    print(x)


    When I run the code from VS Code I get an indexing error: in the for loop the code is trying to access element with index 2 even though the list has length 2. Even stranger, this problem is not present when I run the same code from command line.

    Continue reading...

Compartilhe esta Página