In this post, we are going to implement a stack using Python. We are gonna do it using two ways. The first is by pushing to the end of the list, and pop out the rightmost item. The second is by “pushing” to the leftmost and pop out the leftmost item.
classStack:def__init__(self):self.items=[]defis_empty(self):returnself.items==[]defpush(self,item):self.items.append(item)defpop(self):returnself.items.pop()''' returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified. '''defpeek(self):returnself.items[len(self.items)-1]defsize(self):returnlen(self.items)s=Stack()print(s.is_empty())s.push(4)s.push('dog')print(s.peek())print("\n")print(s.peek())s.push(True)print(s.size())print(s.is_empty())s.push(8.4)print(s.pop())print(s.pop())print(s.size())
push to the front end
1234567891011121314151617181920212223242526
classStack:def__init__(self):self.items=[]defis_empty(self):returnself.items==[]#push, inserting at the front end.defpush(self,item):self.items.insert(0,item)#pop out the leftest item.defpop(self):returnself.items.pop(0)defpeek(self):returnself.items[0]defsize(self):returnlen(self.items)s=Stack()s.push('hello')s.push('true')print(s.pop())print(s.pop())