Implementing a Stack in python

To implement a Stack in python, we simply need to extend the existing list class! Winking smile

class Stack(list):

    def push(self, data):
        self.append(data)

    def tos(self):
        if self:
            return self[-1]

    def peek(self, index):
        if self and 0 <= index < len(self):
            return self[index]

    def __iter__(self):
        if self:
            ptr = len(self) - 1
            while ptr >= 0:
                yield self[ptr]
                ptr -= 1

def main():
    st = Stack()
    st.push(10)
    st.push(20)
    st.push(30)
    st.push(40)
    st.push(50)

    for x, y in enumerate(st):
        print 'Index: {0} Value: {1}'.format(x, y)

    print '\nTop of Stack: ', st.tos()

    print '\n'
    for x in xrange(6):
        print 'Deleting ', st.pop()
        # will throw exception in the last iteration since only 5 items are in stack

    raw_input()

if __name__ == '__main__': main()

Output >>

Index: 0 Value: 50
Index: 1 Value: 40
Index: 2 Value: 30
Index: 3 Value: 20
Index: 4 Value: 10

Top of Stack:  50

Deleting  50
Deleting  40
Deleting  30
Deleting  20
Deleting  10
IndexError: pop from empty list
Press any key to continue . . .

leave your comment