Free Study Material

Data Structure

Introduction

So far, you've mostly stored data in single variables or plain lists. A data structure is a more deliberate way of organizing data — chosen specifically because it makes certain operations (adding, removing, searching, ordering) fast and natural for a particular kind of problem.

Concept

Data structures are broadly grouped into two families:

  • Linear — elements are arranged one after another, in a single sequence (a list, a stack, a queue).
  • Non-linear — elements branch or connect in more complex ways (a tree, a graph).

Class 12 focuses on one linear structure in particular: the stack, which you'll build directly on top of Python's own list.

Explanation

The reason data structures matter isn't storage — a plain list can already hold anything. It's behaviour: a stack doesn't just hold items, it enforces a strict rule about the order you're allowed to add and remove them in. A plain list lets you insert or remove at any position; a stack is the exact same kind of container with one rule bolted on — only the top can ever be touched — which is exactly what the next topic covers.

Note: Choosing the right data structure is about matching how your data needs to behave, not just what it needs to hold. A list stores anything; a stack specifically enforces a last-in-first-out order.

Summary

A data structure organizes data to make specific operations efficient and predictable. Stacks — a linear, order-enforcing structure built on Python's list — are this chapter's focus.

Organizing the Mess

A Data Structure is a specialized way of organizing, storing, and retrieving data in a computer so that it can be used efficiently.

Imagine a library. If books were thrown on the floor randomly, finding one would take forever. If they are organized in shelves (A-Z), finding one is fast. That "Shelf System" is a data structure.

The Two Families

Data structures are broadly classified into two categories:

Type Description Real Life Example
Linear Elements are arranged sequentially, one after another. A line of people waiting for a bus (Queue) or a stack of plates (Stack).
Non-Linear Elements are arranged in a hierarchy or network. A family tree (Tree) or a Google Map network (Graph).

Syllabus Focus: In Class 12, we focus on Stacks, which are a Linear Data Structure.

Introduction

Picture a stack of books on a table: you can only ever add a new book to the top, and you can only ever remove the book currently on top. You can't pull one out from the middle without disturbing everything above it. That's exactly how a stack data structure behaves.

Concept

This behaviour has a name: LIFO — Last In, First Out. Whatever was added most recently is the first thing to come back out. In Python, a plain list already gives you everything a stack needs:

  • .append(item) — adds to the top (this is called a push).
  • .pop() — removes and returns the top item (this is called a pop).

Worked Example

stack = []

stack.append("Book A")
stack.append("Book B")
stack.append("Book C")

print("Current Stack:", stack)

removed = stack.pop()

print("Removed:", removed)
print("Stack after pop:", stack)

removed is "Book C" — the last one pushed — even though "Book A" was added first.

Tip: Nothing about a Python list is a "real" stack — it's the same list you've always used. What makes it a stack is a self-imposed rule: only ever append() or pop() from the same end, never insert() or access the middle.

Summary

A stack follows LIFO: the last item added is the first removed. Python's list, restricted to .append() (push) and .pop() (pop) at one end only, is exactly how a stack is built and used in this course.

The "Pringles" Principle

A Stack is a linear data structure that follows the LIFO rule: Last In, First Out.

Think of a tube of chips. The last chip you put in (at the top) is the first one you must eat. You cannot reach the bottom chip without removing all the ones above it. This strict "Top-Only" access is what makes a Stack unique.

Where are Stacks used?

Stacks aren't just for chips. Your computer uses them everywhere:

  • Undo Button (Ctrl+Z): The last action you did is stored on top. When you press Undo, it pops the top action off to show the previous state.
  • Browser History: When you visit a new page, it is "pushed" to the stack. When you click "Back," you "pop" the current page.
  • Function Calls: When Python runs a function inside a function (Recursion), it stacks them up in memory.
# A simple list acting as a stack
stack = []

# Pushing elements (Last In)
stack.append("Book A")
stack.append("Book B")
stack.append("Book C")

print("Current Stack:", stack)

# Popping element (First Out)
removed = stack.pop() 

print("Removed:", removed) # Should be "Book C"
print("Stack after pop:", stack)

Introduction

Every stack, no matter the language, is built from the same small set of named operations. Knowing their exact names matters for CBSE exams, since questions often ask for the operation by name rather than by describing it.

Concept

  • Push — add an item to the top. In Python: stack.append(item).
  • Pop — remove and return the top item. In Python: stack.pop().
  • Peek (sometimes called Top) — look at the top item without removing it: stack[-1].
  • IsEmpty — check whether the stack has anything in it: len(stack) == 0.

Explanation

Two specific failure conditions have their own exam-standard names, and they only ever happen at the two extremes of a stack's capacity:

  • Stack Underflow — attempting to pop() from a stack that's already empty. There's nothing to remove.
  • Stack Overflow — attempting to push() onto a stack that has run out of space (rare in Python, where lists grow dynamically, but still a standard term to know).

Worked Example

stack = []

def safe_pop(s):
    if len(s) == 0:
        print("Stack Underflow")
    else:
        print("Popped:", s.pop())

safe_pop(stack)  # Stack Underflow -- nothing was pushed yet

stack.append(10)
stack.append(20)
print("IsEmpty:", len(stack) == 0)  # False -- stack has 2 items
print("Peek:", stack[-1])           # 20 -- top item, not removed
safe_pop(stack)                     # Popped: 20
Warning: Calling .pop() on an empty Python list raises a real IndexError and crashes your program. Always check len(stack) == 0 first — that check IS how you prevent Stack Underflow in code.

Summary

Push, Pop, Peek, and IsEmpty are the four named stack operations. Underflow (popping an empty stack) and Overflow (pushing a full one) are their standard failure-condition names — checking len(stack) == 0 before every pop() is how you guard against Underflow in Python.

The Stack Syntax

To implement a Stack in Python, we use a simple List. However, we must use specific methods to ensure we follow the LIFO rule.

Here are the standard definitions you must memorize for the exam:

Operation Python List Method Description
PUSH (Insert) stack.append(item) Adds an element to the Top (End) of the list.
PEEK (View) stack[-1] Returns the Top element without removing it.
POP (Delete) stack.pop() Removes and returns the Top element.

What is Stack Underflow?

Critical Concept: If you try to POP or PEEK from an empty stack, Python will crash with an IndexError.

In Computer Science, attempting to access an empty stack is called Underflow. To prevent this, you must always check if the stack is empty before popping.

Stack Master Sheet

Everything you need to memorize for the exam in one table.

Concept Exam Keyword Python Logic
Structure LIFO (Last In First Out) Use a standard List.
Insert PUSH stack.append(data)
Delete POP stack.pop()
Empty Check Underflow if len(stack) == 0: or if not stack:
# --- 1. THE DATA (Given in Exam) ---
# Format: [ItemNo, Name, Stock]
inventory = [
    [101, "Pen", 50],
    [102, "Pencil", 5],
    [103, "Eraser", 8],
    [104, "Scale", 25]
]

reorder_stack = []

# --- 2. PUSH FUNCTION ---
def Push(items):
    for product in items:
        # Check if Stock (Index 2) is less than 10
        if product[2] < 10:
            # Create a small list [ItemNo, Name]
            data = [product[0], product[1]]
            reorder_stack.append(data)
            print(f"Pushed to Reorder: {data}")

# --- 3. POP FUNCTION ---
def Popitems():
    while True:
        if len(reorder_stack) == 0: # Check Underflow
            print("Stack empty")
            break
        else:
            print("Popped:", reorder_stack.pop())

# --- EXECUTION ---
print("--- Step 1: Pushing Low Stock Items ---")
Push(inventory)

print("\n--- Step 2: Popping Stack ---")
Popitems()
numbers = [12, 5, 8, 19, 20, 7]
stack = []

def PushEven(num_list):
    for n in num_list:
        if n % 2 == 0:  # Logic: Even Number
            stack.append(n)
            print(f"Pushed: {n}")

def PopStack():
    if not stack:  # 'if not stack' is same as 'len(stack)==0'
        print("Stack Underflow")
    else:
        while stack:
            print("Popped:", stack.pop())

# Run
PushEven(numbers)
print("\nEmptying Stack:")
PopStack()

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access