Implementation of Stack in Python

Posted by Python Pool on February 7th, 2020

A Python stack represents a sequence of objects or elements in a linear data structure format. The stack consists of a bounded bottom and all the operations are carried out on the top position. Whenever an element is added to the stack by the push operation, the top value is incremented by one, and when an element is popped out from the stack, the top value is decremented by one. A pointer to the top position of the stack is also known as the stack pointer.

 

A Python stack may be fixed in size or may have a dynamic implementation where the size is allowed to change. In the case of bounded capacity stacks, trying to add an element to an already full stack causes a stack overflow exception. Similarly, a condition where a pop operation tries to remove an element from an already empty stack is known as underflow.

Operations We Can Perform On Python Stack

A stack is considered to be a restricted data structure as only a limited number of operations are allowed. Besides the push and pop operations, certain implementations may allow for advanced operations such as:

  • Push: Adds an item in the stack. Once the stack is full, it is said to be in an Overflow condition.
  • Pop: Removes an item from the stack. It follows a reversed order to pop items similar to the way when items are pushed. It is said to be an Underflow condition.
  • Peek: View the topmost item in the stack.
  • Duplicate: Copy the top item’s value into a variable and push it back into the stack.
  • Swap: Swap the two topmost items in the stack.
  • Rotate: Move the topmost elements in the stack as specified by a number or move in a rotating fashion.

Software implementations of the stack concept are done using arrays and linked lists where the top position is tracked using a variable or header pointer respectively. Many programming languages provide built-in features to support stack implementation.

Hardware stacks are implemented for the purpose of memory allocation and access using a fixed origin and size. Stack registers are used to store the value of the stack pointer.

Push Operation in Python Stack

The process of putting a new data element onto the stack is known as a Push Operation. Push operation involves a series of steps −

 Read The Full Article: Python  Stack

Like it? Share it!


Python Pool

About the Author

Python Pool
Joined: February 7th, 2020
Articles Posted: 1