Ch 3 introduces the stack data structure — a linear, LIFO (Last In, First Out) collection. Learn operations (push, pop, peek), implementation using Python lists, and real-world applications.
Stack: a linear data structure following LIFO — the last element added is the first removed. Think: stack of plates. Operations: push(item) — add to top, pop() — remove and return top item, peek()/top() — view top without removing, isEmpty() — True if stack is empty, size() — number of elements. Underflow: trying to pop from empty stack. Overflow: stack exceeds maximum size (for fixed-size implementations).
Using Python list: stack = []; stack.append(item) for push; stack.pop() for pop; stack[-1] for peek; len(stack) for size; len(stack)==0 for isEmpty. Applications: browser back button (pages pushed, popped), undo in editors, function call stack (recursion), expression evaluation (infix to postfix), balanced parentheses checker, reversing a sequence. Example: parentheses check — push when "(", pop when ")"; at the end, stack should be empty.
Download: https://ncert.nic.in/textbook/pdf/lecs103.pdf | Complete Book: https://ncert.nic.in/textbook/pdf/lecs1ps.zip
When a function is called, Python creates a "stack frame" containing: local variables, parameters, return address. This frame is pushed onto the call stack. When the function returns, its frame is popped. For recursion: each recursive call adds a new frame — that's why recursion uses memory proportional to depth. Stack overflow: too many recursive calls (Python limit: ~1000). The call stack is why local variables of different function calls don't interfere with each other — each has its own frame.
Book a Trial + Diagnostic session. Get a personalized Learning Path with clear milestones, tutor match, and a plan recommendation — all within 24 hours.
Book Trial + Diagnostic →