Stack in Python:
--------------------------
Stack is a Abstract Data Type. Abstract is a Latin word the meaning is "Pulled away". Stack is similar to array just the difference is in the way of adding and removing the items.
Stack is an ordered collection of items where the addition of new item and removal of existing item always takes at same end. This end is commonly referred as TOP. The most recently added item is the one that is in the position of removed first this ordering principle is called Last in first out (LIFO).
To understand this LIFO Principle check the below set of plates. consider single plate in set as an item that you want to insert in Stack, now if you want to add item which is a plate in this example you need to put it on TOP. and one by one you can start updating items. Now if you want a plate from set which is 3rd last from Top then you need to remove the plates one by one from top. similarly if you need to get one item from stack then you need to remove items from top. This is Last in First out principle.
In stack addition of item called Push and removal of item called Pop. Stacks are fundamentally very important as they can be used to reverse the order of Item.
A stack can be easily implemented either through an array or a Linked list. Before going in actual implementation of stack we will go through some actions that we need to perform in Stack.
Queue in Python Implemented by :
1) List
2) queue library
Methods in Stack:
stack() - It create new stack
push(item) - It add item at top, it takes item as a parameter
pop() - It removes the item from top
peek() - It return top item from stack but does not remove it.
isEmpty() - Its test to see stack is empty, It return Boolean value
siza() - It returns the number of items in stack
Actual Implementation of Stack in Python Using List:
class Stack(object):
def __init__(self):
self.items = []
def push(self,item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items ==[]
def size(self):
return len(self.items)
def peek(self):
return self.items[len(self.items)-1]
s= Stack()
print(s.isEmpty()) # checking the created stack is empty
s.push(1)
s.push(4)
s.push("parsh") #ading string
print(s.pop()) # it should print the latest added item
print(s.size()) #printing Size of stack
The out put of above Actions
True (output of isEmpty)
parsh(Pop action )
2(after pop action the size of stack)