Implementing a Stack in Python.

27 May 2016

In previous posts, I have implemented a binary search tree and a singly linked list. In this post I will try to implement a Stack in Python.

Stack:

In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed. The order in which elements come off a stack gives rise to its alternative name, LIFO (for last in, first out). 1

Basically there are two ways to represent a stack.

As an array.

As a singly linked list.

Here I will try to implement an array based stack. Now let’s define a stack class.

The code is fairly straight forward. The __init__ function is the constructor of Stack class. size represents the maximum number of elements which the stack can contain. And the array arr holds the actual elements of the stack.

Now let’s implement the basic operations one by one.

Inserting an element onto the stack

As the stack follows LIFO principle, we push all incoming elements to the end of the array.

defpush(self,item):iflen(self.arr)==self.size:print"Stack is full."else:self.arr.append(item)