What is a stack?
Stack is a data structure which follows the *LIFO * property, which means Last-In-First-Out. The element inserted last will be the first to be removed.
Stack operations
Push- To insert new element in the stack.
Pop- To remove an element from the stack.
Using python list as stack
We can use the python's in-built list as stack data structure.
Push
You can use the in-built append method to insert element at the end of the array/list.
stack = []
stack.append(3)
stack.append(4)
stack.append(5)
stack.append(6)
print(stack) # [3, 4, 5, 6]
Pop
To pop an element we can use the in-built pop
method on list.
print(stack.pop()) # 6
This method will remove the last element in the list, if we do not specify any element to be removed.
Getting top of stack
To get the top element in the stack we can use a python's in-built feature to index list from the end.
print(stack[-1]) # 5
Top comments (0)