You are on page 1of 11

Unit Python - Stack Data Structure

Module DATA STRUCTURES AND ALGORITHMS


CC 104 Data Structures and Algorithms Units: 80hrs Page |1

INFORMATION SHEET CC 104-9.1.1


“Python - Stack Data Structure”

In this lesson, you will learn about the stack data structure and its implementation in
Python.

References:
Book:
• Data Structures and Algorithms
By: Cecil Jose A. Delfinado
Links:

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |2

INFORMATION SHEET CC 104-9.1.1


“Python - Stack Data Structure”

A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This
means the last element inserted inside the stack is removed first.
You can think of the stack data structure as a pile of plates on top of one another.

Stack representation similar to a pile of plate


Here, you can:

 Put a new plate on top


 Remove the top plate

And, if you want the plate at the bottom, you must first remove all the plates on top. This is
exactly how the stack data structure works.

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |3

LIFO Principle of Stack

In programming terms, putting an item on top of the stack is called push and removing
an item is called pop.

Stack Push and Pop Operations


In the above image, although item 3 was kept last, it was removed first. This is exactly
how the LIFO (Last In First Out) Principle works.
We can implement a stack in any programming language like C, C++, Java, Python or C#, but the
specification is pretty much the same.

Basic Operations of Stack

There are some basic operations that allow us to perform different actions on a stack.

 Push: Add an element to the top of a stack


 Pop: Remove an element from the top of a stack
SUBJECT TEACHER: APPROVED FOR
IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |4

 IsEmpty: Check if the stack is empty


 IsFull: Check if the stack is full
 Peek: Get the value of the top element without removing it

Working of Stack Data Structure

The operations work as follows:

1. A pointer called TOP is used to keep track of the top element in the stack.
2. When initializing the stack, we set its value to -1 so that we can check if the stack is empty
by comparing TOP == -1.
3. On pushing an element, we increase the value of TOP and place the new element in the
position pointed to by TOP.
4. On popping an element, we return the element pointed to by TOP and reduce its value.
5. Before pushing, we check if the stack is already full

6. Before popping, we check if the stack is already empty

Working of Stack Data Structure

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |5

Stack Implementations in Python

The most common stack implementation is using arrays, but it can also be implemented
using lists.

# Stack implementation in python

# Creating a stack
def create_stack():
stack = []
return stack

# Creating an empty stack


def check_empty(stack):
return len(stack) == 0

# Adding items into the stack


def push(stack, item):
stack.append(item)
print("pushed item: " + item)

# Removing an element from the stack


def pop(stack):
if (check_empty(stack)):
return "stack is empty"

return stack.pop()

stack = create_stack()
push(stack, str(1))
SUBJECT TEACHER: APPROVED FOR
IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |6

push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))

Using append and pop

list=[]
list.append(1) # append 1
print("push:",list)
list.append(2) # append 2
print("push:",list)
list.append(3) # append 3
print("push:",list)
list.pop() # pop 3
print("pop:",list)
print("peek:",list[-1]) # get top most element
list.pop() # pop 2
print("pop:",list)
print("peek:",list[-1]) # get top most element

Implementation using list:


Python’s built-in data structure list can be used as a stack. Instead of push(), append() is
used to add elements to the top of the stack while pop() removes the element in LIFO order.

# Python program to
# demonstrate stack implementation
# using list

stack = []

# append() function to push


# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
SUBJECT TEACHER: APPROVED FOR
IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |7

print('Initial stack')
print(stack)

# pop() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)

# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty

Implementation using collections.deque:


Python stack can be implemented using the deque class from the collections module.
Deque is preferred over the list in the cases where we need quicker append and pop operations
from both the ends of the container.
# Python program to
# demonstrate stack implementation
# using collections.deque

from collections import deque

stack = deque()

# append() function to push


# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack:')
print(stack)

# pop() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |8

print(stack.pop())

print('\nStack after elements are popped:')


print(stack)

# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty

Implementation using queue module


Queue module also has a LIFO Queue, which is basically a Stack. Data is inserted into
Queue using the put() function and get() takes data out from the Queue.

There are various functions available in this module:

maxsize – Number of items allowed in the queue.


empty() – Return True if the queue is empty, False otherwise.
full() – Return True if there are maxsize items in the queue. If the queue was initialized with
maxsize=0 (the default), then full() never returns True.
get() – Remove and return an item from the queue. If the queue is empty, wait until an item is
available.
get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available
before adding the item.
put_nowait(item) – Put an item into the queue without blocking. If no free slot is immediately
available, raise QueueFull.
qsize() – Return the number of items in the queue.

# Python program to
# demonstrate stack implementation
# using queue module

from queue import LifoQueue

# Initializing a stack
stack = LifoQueue(maxsize=3)

# qsize() show the number of elements


# in the stack
print(stack.qsize())

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs Page |9

# put() function to push


# element in the stack
stack.put('a')
stack.put('b')
stack.put('c')

print("Full: ", stack.full())


print("Size: ", stack.qsize())

# get() function to pop


# element from stack in
# LIFO order
print('\nElements popped from the stack')
print(stack.get())
print(stack.get())
print(stack.get())

print("\nEmpty: ", stack.empty())

Applications of Stack Data Structure

Although stack is a simple data structure to implement, it is very powerful. The most
common uses of a stack are:

 To reverse a word - Put all the letters in a stack and pop them out. Because of the LIFO
order of the stack, you will get the letters in reverse order.
 In compilers - Compilers use the stack to calculate the value of expressions like 2 + 4 / 5
* (7 - 9) by converting the expression to prefix or postfix form.
 In browsers - The back button in a browser saves all the URLs you have visited
previously in a stack. Each time you visit a new page, it is added on top of the stack. When you
press the back button, the current URL is removed from the stack, and the previous URL is
accessed.

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs P a g e | 10

STUDENT NAME: __________________________________ SECTION: __________________

PERFORMANCE TASK CC 104-9.1.1


WRITTEN WORK TITLE: “Stack Data Structure”

WRITTEN TASK OBJECTIVE:


MATERIALS:
 Pen and Paper
TOOLS & EQUIPMENT:
 None
ESTIMATED COST: None

Procedure/Instruction:

PRECAUTIONS:
 Do not just all your output from the internet.
 Use citation and credit to the owner if necessary.
ASSESSMENT METHOD: WRITTEN WORK CRITERIA CHECKLIST

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director
Unit Python - Stack Data Structure
Module DATA STRUCTURES AND ALGORITHMS
CC 104 Data Structures and Algorithms Units: 80hrs P a g e | 11

STUDENT NAME: __________________________________ SECTION: __________________

PERFORMANCE TASK CRITERIA CHECKLIST CC 104-9.1.1

CRITERIA SCORING
Did I . . .
1 2 3 4 5
1. Focus - The single controlling point made with an awareness of task
about a specific topic.
2. Content - The presentation of ideas developed through facts, examples,
anecdotes, details, opinions, statistics, reasons and/or opinions
3. Organization – The order developed and sustained within and across
paragraphs using transitional devices and including introduction and
conclusion.
4. Style – The choice, use and arrangement of words and sentence
structures that create tone and voice.
5. .
6. .
7. .
8. .
9. .
10. .
TEACHER’S REMARKS:  QUIZ  RECITATION  PROJECT

GRADE:

5 - Excellently Performed
4 - Very Satisfactorily Performed
3 - Satisfactorily Performed
2 - Fairly Performed
1 - Poorly Performed

_______________________________
TEACHER

Date: ______________________

SUBJECT TEACHER: APPROVED FOR


IMPLEMENTATION:
MODULE 9th
MIDTERM MR. NOEL JERIC D. DE GUIA
9 Meeting
Subject Teacher MR. WILBERT A. MAÑUSCA
School Director

You might also like