Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__getitem__ invocation in for loop

Tags:

python

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)

   def pop(self):
       return self.items.pop()

   def __getitem__(self,index):
       print "index",index
       return self.items[index]

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


stack = Stack()
stack.push(2)
stack.push(1)
stack.push(0)

for item in stack:
    print item

and the output

index 0
2
index 1
1
index 2
0
index 3

Why is getitem called four times?

like image 648
Lukasz Madon Avatar asked Dec 12 '22 07:12

Lukasz Madon


1 Answers

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.

class Stack(list):
    push = list.append
like image 141
kindall Avatar answered Dec 28 '22 22:12

kindall