Skip to content
Skip to page content
soylai.com

Data Structure: Stack — Notes

6 sections 6 min readBeta

1. Data structures and the stack

A data structure is a way of organising data so it can be used efficiently (list, dictionary, stack, queue).

A stack is a linear structure with one open end, the top. Items are added (push) and removed (pop) only at the top, so the item added last is removed first: LIFO, Last In First Out. Everyday examples: a pile of plates or books, bangles on a wrist, the undo history of an editor.

A data structure is a way of organising data so that it can be used efficiently.
StructureHow items are added and removedEveryday picture
ListAt any position, by indexA numbered register
StackOnly at one end, the top (LIFO)A pile of plates
QueueAdded at the rear, removed from the front (FIFO)A ticket-counter line
DictionaryBy keyA phone directory
Each column is the stack after one operation; arrows show the value returned.

Key terms

Data structure

An organised way of storing data so that it can be accessed and changed efficiently.

Stack

A linear data structure where insertion and deletion happen at one end, the top.

LIFO

Last In, First Out: the most recently added item is removed first.

2. Operations and a list implementation

OperationList code
Push xstk.append(x)
Popstk.pop() (removes and returns the last item)
Peek / topstk[-1]
Is emptystk == [] or len(stk) == 0
Sizelen(stk)

The end of the list is the top. Standard functions:

def push(stk, item):
    stk.append(item)

def pop(stk):
    if stk == []:
        return "Underflow"
    return stk.pop()

def peek(stk):
    if stk == []:
        return None
    return stk[-1]

def is_empty(stk):
    return stk == []

Running push twice and pop three times on a list of books gives Diary Diary Atlas Underflow: the third pop reports underflow.

Table of stack operations: push uses append, pop uses pop, peek reads index minus one, is-empty compares with an empty list, and size uses len
OperationMeaningWith a list stk
PushAdd an item at the topstk.append(x)
PopRemove and return the top itemstk.pop()
Peek (top)Read the top item without removing itstk[-1]
isEmptyIs the stack empty?stk == [] or len(stk) == 0
SizeNumber of itemslen(stk)
The third pop finds the stack empty and returns the underflow message instead of crashing.
CallResult
peek(books)Diary
pop(books) three timesDiary, Atlas, Underflow
is_empty(books)True

Key terms

Push

Adding an item at the top of the stack (append for a list).

Pop

Removing and returning the top item (list pop with no argument).

Peek

Reading the top item without removing it (index -1).

3. Underflow and overflow

Underflow: pop or peek on an empty stack. With a list, pop() on [] stops the program with IndexError: pop from empty list, so test if stk == []: first and report "Underflow" (then return, so the pop line is not reached).

Overflow: push on a full stack of fixed capacity, tested with len(stk) == capacity. A Python list grows as needed, so overflow does not occur in normal list programs; it matters when a size limit is set (a tray holder for four trays, the last 20 messages).

Table comparing underflow, popping or peeking an empty stack, which must be checked before calling pop, with overflow, pushing onto a full fixed-size stack, which a growing Python list does not suffer
ConditionWhen it happensWhat the program does
UnderflowPop or peek on an empty stackCheck stk == [] first; otherwise Python stops with IndexError: pop from empty list
OverflowPush on a full fixed-size stackCheck len(stk) == capacity first; a plain Python list grows, so it does not overflow in normal use
Safe pop

Key terms

Underflow

An attempt to pop or peek from an empty stack.

Overflow

An attempt to push onto a full stack of fixed size.

4. Displaying and tracing a stack

Display from the top down by counting the index down:

def display(stk):
    if stk == []:
        print("Stack is empty")
    else:
        for i in range(len(stk) - 1, -1, -1):
            print(stk[i])

For [3, 8, 5] it prints 5, 8 and 3 on separate lines.

Tracing: write the stack as a list with the top on the right; push adds on the right, pop removes the rightmost item and returns it. Popped items always come out in reverse order of their pushes.

range(len(stk) - 1, -1, -1) counts down from the top index to 0.
i (from top)Printed
25
18
03
Generated by running the operations in Python.
StepOperationStack (bottom → top)Returned
1push A['A']—
2push B['A', 'B']—
3pop['A']B
4push C['A', 'C']—
5push D['A', 'C', 'D']—
6pop['A', 'C']D
7pop['A']C

Key terms

Trace (dry run)

Following a program by hand and writing the stack after every operation.

5. Applications

  • Reversing text, a list or the digits of a number: push all, pop all.
  • Bracket matching: push opening brackets; for a closing one pop and compare; the stack must be empty at the end.
  • Function calls: Python keeps active calls on a call stack; the latest call returns first.
  • Undo and back buttons: push each action or page; undo or back pops the latest.
  • Postfix evaluation: push numbers; an operator pops the right operand, then the left, and pushes the result. 4 5 + 2 * evaluates to 18.
  • Decimal to binary: push remainders of division by 2; popping gives the binary digits (11 gives 1011).
Table of stack applications: reversing text pushes characters, bracket checking pushes opening brackets, function calls push active calls, undo and back push actions or pages, and postfix evaluation pushes operands
ApplicationWhat is pushedWhy LIFO fits
Reversing textEach characterThe last character comes out first
Bracket checkingEach opening bracketA closing bracket must match the latest open one
Function callsEach active callThe latest call finishes first
Undo / BackEach action or pageThe latest action is undone first
Postfix evaluationEach operandAn operator uses the two latest operands
Only brackets change the stack; other characters are ignored.
Bracket readActionStack after
{push{
[push{[
(push{[(
)pop ( matches{[
]pop [ matches{
}pop { matchesempty
endstack empty
Value: 18. Postfix writes the operator after its operands.
TokenActionStack after
4push[4]
5push[4, 5]
+pop 5 and 4, push 9[9]
2push[9, 2]
*pop 2 and 9, push 18[18]

Key terms

Postfix expression

An expression in which each operator follows its two operands, such as 4 5 + for 4 + 5.

Call stack

The stack Python uses to keep track of functions that have been called but not yet finished.

6. Board-style push and pop programs

A typical question gives a list or dictionary and asks for two functions:

  1. push: loop over the data, test the stated condition, and append the items (or keys) that pass.
  2. pop: loop while the stack is not empty, pop and display each item, then print the message asked for (such as "Stack Empty").
def push_cities(towns, stk):
    for name, pin in towns.items():
        if pin % 2 == 1 and len(name) > 4:
            stk.append(name)

def pop_cities(stk):
    while stk != []:
        print(stk.pop(), end=" ")
    print("| None left")

towns = {"Shimla": 171001, "Ooty": 643001, "Kohima": 797002, "Madurai": 625003, "Bhuj": 370001}
S = []
push_cities(towns, S)
print(S)
pop_cities(S)

Output:

['Shimla', 'Madurai']
Madurai Shimla | None left
Imagined task; PIN codes used only as sample numbers.
TownPIN odd?More than 4 letters?Pushed?
Shimlayesyesyes
Ootyyesnono
Kohimanoyesno
Maduraiyesyesyes
Bhujyesnono
The two-function pattern

Key terms

Condition

The test in the question that decides which items are pushed.

Exam tips

Common mistakes

  • Using stk.push(x): lists have no push method; use append.
  • Popping without checking for an empty stack (IndexError).
  • Printing a "Underflow" message but not returning, so the pop still runs.
  • Displaying the stack bottom first when the question asks for top first.
  • Forgetting that popped items come out in reverse order.
  • In postfix, popping the operands in the wrong order for - and //.

How marks are usually awarded

  • Output questions: each correct line or value as stated.
  • Error-finding: ½ or 1 mark for each error found and corrected.
  • Push/pop programs (3–5 marks): loop and condition, push, underflow check, pop loop with display, message.
  • Theory: one point per mark, with an example.