Implement Last-In First-Out Stacks
Core idea
A stack removes the most recently added item (LIFO). Use list.append to push and list.pop() to remove the top; a[-1] peeks without removal. End operations are amortized O(1) for a Python list (individual growth may cost more). Define what an empty pop means for your application.
history = []history.append('rename')history.append('move')print(history[-1])print(history.pop())print(history)Peeking leaves both entries; popping removes only move.
Check nested delimiters
def balanced(text): stack = [] for ch in text: if ch == '(': stack.append(ch) elif ch == ')': if not stack: return False stack.pop() return not stackprint(balanced('(())'))print(balanced(')('))Every closing delimiter must match an earlier unmatched opening delimiter. An empty stack at the end means all opens are matched. Non-parenthesis text is ignored.
Common mistake
Do not pop an empty list unless IndexError is the intended contract. A stack checks nesting order, not just equal counts.
Practice
Extend the checker to square brackets using a mapping of closing to opening symbols; test ([)] and ([]).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stack
Check your understanding of stack.
What is printed?
a=['A','B'];print(a.pop())What is printed?
a=[2,4];print(a[-1],len(a))What distinguishes LIFO?
Why is )( invalid despite equal counts?