Stack and Queues in Python¶

Data structures organize storage in computers so that we can efficiently access and change data. Stacks and Queues are some of the earliest data structures defined in computer science.

Stack¶

Stacks, like the name suggests, follow the Last-in-First-Out (LIFO) principle. It is a linear data structure which follows a particular order in which the operations are performed. As if stacking plates one on top of the other, the last plate we put on the top is the one that is the first to be removed from the stack later.

Basic operations you can perform in a stack¶

  • Push - Adds an element to the top of the stack.
  • Pop - Removes the element at the top of the stack.
  • Peek or top - Look at the top of the stack

Implementing Stack using list¶

In [1]:
stack = [] 

Function to print top element of stack¶

In [2]:
def top(stack):
    if stack != []:
        print("{} is top element".format(stack[-1]))
    else:
        print("Stack Empty!!!")

Function to print size of stack¶

In [3]:
def size(stack):
    print("Size of stack is {}".format(len(stack)))

Function to check if a stack is empty¶

In [4]:
def empty(stack):
    if stack == []:
        return True
    else:
        return False

Function to Push element into stack¶

In [5]:
def push(stack, value):
    stack.append(value)
    print("Pushed {} into stack".format(value))

Function to Pop elements from stack¶

In [6]:
def pop(stack):
    if not empty(stack):
        print("{} is popped".format(stack.pop()))
    else:
        print("Cannot Pop since stack is empty")

Function to print the complete stack¶

In [8]:
def show_stack(stack):
    print("Full stack is {}".format(stack))

Taking Stacks out for a spin¶

In [9]:
# Pushing elements into a stack
push(stack, 1)
push(stack, 2)
push(stack, 3)

# Printing stack
show_stack(stack)

# Printing stack size
size(stack)

# Printing top of stack
top(stack)

# Popping elements from a stack
pop(stack)

show_stack(stack) 

# Check if stack is empty
empty(stack)

# More popping elements from a stack
pop(stack)
pop(stack)
# The below line would fail since there are no more elements to pop from a stack
pop(stack)

show_stack(stack)

empty(stack)
Pushed 1 into stack
Pushed 2 into stack
Pushed 3 into stack
Full stack is [1, 2, 3]
Size of stack is 3
3 is top element
3 is popped
Full stack is [1, 2]
2 is popped
1 is popped
Cannot Pop since stack is empty
Full stack is []
Out[9]:
True
In [ ]: