Skip to content Skip to sidebar Skip to footer

__getitem__ Invocation In For Loop

I am learning Python I don't get one thing. Consider this code: class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item)

Solution 1:

The for loop doesn't know how to iterate over your object specifically because you have not implemented __iter__(), so it uses the default iterator. This starts at index 0 and goes until it gets an IndexError by asking for index 3. See http://effbot.org/zone/python-for-statement.htm.

Your implementation would be a lot simpler if you derived from list, by the way. You wouldn't need __init__(), pop(), or __getitem__(), and push could be just another name for append. Also, since list has a perfectly good __iter()__ method, for will know how to iterate it without going past the end of the list.

classStack(list):
    push = list.append

Post a Comment for "__getitem__ Invocation In For Loop"