You could use something like this (warning: this is a naive implementation - it doesn't perform checks on the arguments passed):
class Stack(object):
def __init__(self):
self._stack = [] # Allocate an empty list
def push(self, ele):
self._stack += [ele] # Use list concatenation to emulate the `push` operation
def pop(self):
last = self._stack[-1:] # Return the last element of the list (also works for empty lists)
self._stack = self.stack[0:-1] # Copy the elements from the beginning of the list to the last element of the list
return last # return the last element
# All stacks should have the `size` function to determine how many elements are
# in the stack:
def size(self):
return len(self._stack)
# Occasionally you'll want to see the contents of the stack, so we have to
# implement the `__str__` magic method:
def __str__(self):
return '[%s]' % ','.join(map(str, self._stack))
NOTE: This method doesn't use any of the list methods as append and pop.
EXAMPLE:
s = Stack()
# fill the stack with values:
for i in xrange(10):
s.push(i+1)
print s # Outputs: [1,2,3,4,5,6,7,8,9,10]
s.pop()
s.pop()
print s # Outputs: [1,2,3,4,5,6,7,8]
stack[len(stack)]will always fail ifstackis alist