Stack
A Stack in Python
A Python list makes a natural stack if its end is treated as the top: append(x) pushes and pop() (with no argument) removes and returns the last element. The book builds the operations as small functions — isEmpty returns len(stack) == 0, size returns len(stack), top (also called peek) returns stack[-1] without removing it, and display prints the elements from the top down. Each function that pops or peeks first checks isEmpty, which is how underflow is avoided.
Reversing a word with a stack — this prints KCATS:s = []for ch in "STACK": s.append(ch)r = ""while s: r += s.pop()print(r)
A Python list makes a natural stack if its end is treated as the top: append(x) pushes and pop() (with no argument) removes and returns the last element. The book builds the operations as…
Infix, Prefix and Postfix Notation
We normally write the operator between its operands — infix notation, as in A + B. Infix needs precedence rules and parentheses to say what is done first: in A + B * C the multiplication happens first, and (A + B) * C forces the addition first. Two other notations put the operator elsewhere. In prefix (Polish) notation the operator comes before its operands: + A B. In postfix (reverse Polish) notation it comes after them: A B +. Postfix and prefix need no parentheses at all, because the position of each operator already fixes the order of evaluation — which is why computers convert to postfix before evaluating.
| Infix | Prefix | Postfix |
|---|---|---|
A + B | + A B | A B + |
A + B * C | + A * B C | A B C * + |
A * B + C | + * A B C | A B * C + |
(A + B) * (C - D) | * + A B - C D | A B + C D - * |
A - B + C | + - A B C | A B - C + |
We normally write the operator between its operands — infix notation, as in A + B. Infix needs precedence rules and parentheses to say what is done first: in A + B * C the multiplication…
Converting Infix to Postfix, and Evaluating Postfix
Infix to postfix — the stack holds operators. Scan the infix expression from left to right. An operand goes straight to the output. A left parenthesis is pushed. A right parenthesis pops operators to the output until the matching left parenthesis, which is popped and discarded. An operator first pops to the output every operator on top of the stack with higher or equal precedence, then is pushed itself. When the scan ends, pop whatever remains onto the output. For A + B * C: A out; + pushed; B out; * has higher precedence than +, so it is pushed on top; C out; end — pop * then +, giving A B C * +.
Evaluating postfix — the stack holds operands. Scan from left to right. Push each operand. On an operator, pop two values — the first popped is the right operand, the second the left — apply the operator and push the result. At the end exactly one value remains, the answer. For 6 2 3 + * 4 -: push 6, 2, 3; + pops 3 and 2 and pushes 5 → [6, 5]; * pops 5 and 6 and pushes 30; push 4; - pops 4 and 30 and pushes 30 − 4 = 26.
8 2 / the first value popped is 2 and the second is 8, so the operation is 8 / 2 = 4, not 2 / 8. Reversing the two operands changes nothing for + and *, which is exactly why the paper sets its evaluation questions with − and /.- Stack holds operators
- Operand goes straight to output
- Operator pops higher or equal precedence
- At the end, pop what remains
- A + B * C gives A B C * +
- Stack holds operands
- Each operand is pushed
- Operator pops two; first popped is right
- Exactly one value remains
- 6 2 3 + * 4 - gives 26
Infix to postfix — the stack holds operators. Scan the infix expression from left to right. An operand goes straight to the output. A left parenthesis is pushed. A right parenthesis pops…
Worked Trace: Evaluating a Postfix Expression
Evaluate the postfix expression 5 6 2 + * 12 4 / - with a stack. Read left to right: push 5, push 6, push 2. The operator + pops 2 and then 6, adds them and pushes 8, so the stack is [5, 8]. The operator * pops 8 and then 5 and pushes 40. Push 12 and 4; the operator / pops 4 first and then 12, so it computes 12 / 4 = 3 and pushes it, giving [40, 3]. Finally - pops 3 then 40 and computes 40 − 3 = 37. The same expression in infix is 5 * (6 + 2) - 12 / 4. Note the order for the non-commutative operators: the value popped first is the right operand, so the first pop is the divisor or the subtrahend.
| Token | Action | Stack |
|---|---|---|
| 5, 6, 2 | push | [5, 6, 2] |
| + | pop 2, 6; push 8 | [5, 8] |
| * | pop 8, 5; push 40 | [40] |
| 12, 4 | push | [40, 12, 4] |
| / | pop 4, 12; push 3 | [40, 3] |
| - | pop 3, 40; push 37 | [37] |
Evaluate the postfix expression 5 6 2 + * 12 4 / - with a stack. Read left to right: push 5, push 6, push 2. The operator + pops 2 and then 6, adds them and pushes 8, so the stack is [5…
Key takeaways
- A stack adds and removes at one end, the TOP, so it is LIFO; PUSH adds, POP removes the top.
- Pushing onto a full stack is overflow; popping an empty stack is underflow — check isEmpty before every pop.
- With a Python list as a stack, append() pushes, pop() pops and stack[-1] peeks at the top.
- Stacks reverse data, power undo and the back button, and check that brackets are balanced.
- Prefix puts the operator first, postfix last; neither needs parentheses. A + B * C is A B C * + in postfix.
- In conversion the stack holds operators; in evaluation it holds operands, and the first value popped is the right operand.
Practice questions (25)
Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.
What is the output of the following code?
s = []for ch in "STACK":s.append(ch)r = ""while s:r += s.pop()print(r)Show answer
Answer: B — KCATS
The loop pushes S, T, A, C, K, leaving K on top; the while loop then pops until the list is empty, taking K first and S last, so r becomes KCATS — a stack reverses whatever passes through it. STACK would need first-in-first-out removal, which is a queue, and K alone forgets that the while loop keeps popping until the stack is empty.What is the postfix form of the infix expression A + B * C?
Show answer
Answer: D — `A B C * +`
Multiplication outranks addition, so B * C is formed first and written B C *; adding A to that result gives A B C * +. A B + C * is the postfix of (A + B) * C, the reading that ignores precedence. + A * B C is a correct form of the same expression, but in prefix notation, not postfix.Convert the infix expression (A + B) * (C - D) to postfix.
Show answer
Answer: A — `A B + C D - *`
Each bracket becomes a unit first: A + B is A B + and C - D is C D -; the * joining them comes after both, giving A B + C D - *. The prefix form * + A B - C D is correct notation of the wrong kind. Writing * between the two halves is still thinking in infix, and gathering all four operands before any operator changes which values each operator combines.
Show the other 22 questions
Using a stack, evaluate the postfix expression 6 2 3 + * 4 -
Show answer
Answer: C — 26
Push 6, 2 and 3; + pops 3 and 2 and pushes 5; * pops 5 and 6 and pushes 30; push 4; - pops 4 then 30 and computes 30 − 4 = 26. The answer −26 subtracts in the order the values were popped, 4 − 30, forgetting that the first value popped is the right operand. 14 comes from multiplying 6 by 2 before the addition has been done.On an empty stack the operations push(5), push(8), pop(), push(3), push(9), pop(), pop() are performed in that order. In what order do the elements come out?
Show answer
Answer: B — 8, 9, 3
After 5 and 8 are pushed, the first pop removes 8; 3 and 9 are then pushed on top of 5, so the next two pops remove 9 and then 3, leaving 5 on the stack. The order 8, 3, 9 removes the later items in the order they arrived, which is queue behaviour, and 5, 8, 3 starts from the bottom of the stack instead of its top.What is the condition called when a program tries to pop an element from an empty stack?
Show answer
Answer: C — Underflow
Removing from a stack that holds nothing is underflow, and a stack function avoids it by checking isEmpty before popping. Overflow is the opposite case, pushing onto a stack that is already full. Collision is a hashing term for two keys landing in one slot, and deadlock describes processes waiting on each other — neither is a stack condition.Assertion (A): A postfix expression never needs parentheses to show the order in which its operations are performed. Reason (R): In postfix notation the position of each operator relative to its operands fixes the order of evaluation.
Show answer
Answer: A — Both A and R are true, and R is the correct explanation of A
In postfix an operator acts on the two values immediately before it on the stack, so where it stands decides when it is applied — A B + C * and A B C * + mean different things without any brackets. That positional rule is the reason parentheses are unnecessary, so R explains A. Choosing "R is not the explanation" overlooks that precedence and brackets are exactly what the position replaces.What is printed by the following code?
stack = [10, 20, 30]stack.append(stack.pop() + stack[-1])print(stack)Show answer
Answer: D — `[10, 20, 50]`
Python evaluates the left operand first: stack.pop() removes and returns 30, leaving [10, 20], so stack[-1] is now 20; their sum 50 is appended, giving [10, 20, 50]. The answer with 60 reads stack[-1] as 30, as if the pop had not yet happened. Keeping 30 in the list forgets that pop removes the element, and [10, 50] removes 20 as well, which peeking with [-1] never does.A stack works on the principle of:
Show answer
Answer: A — Last In First Out (LIFO)
The most recently inserted element is removed first in a stack. FIFO describes a queue, the usual confusion.In Python, a push operation on a stack implemented as a list is done using:
Show answer
Answer: A — append()
append() adds an element at the end, which is the top. pop() is the removal operation.Which of the following is an application of a stack?
Show answer
Answer: A — Undo operation in an editor
Undo reverses the latest action first, which is LIFO. Printing and serving in order of arrival are queue behaviours.In a stack, the operation that only looks at the top element without removing it is called:
Show answer
Answer: A — peek
peek reads the top element and leaves it in place. pop removes it, which is the usual mix-up.What is the output of the following code?
s = []s.append(1)s.append(2)s.append(3)s.pop()print(s, len(s))Show answer
Answer: B — [1, 2] 2
Three pushes make [1, 2, 3] and pop() removes the top element 3, leaving [1, 2] 2. "[2, 3] 2" removes the bottom element and "[1, 2] 1" misreads the length.The postfix form of the infix expression A * B + C is:
Show answer
Answer: A — A B * C +
A * B is converted first to A B *, then C and + are appended: A B * C +. "A B C * +" would be the postfix of A + B * C.What is the output of the following code?
st = []for c in "ABC":st.append(c)print(st.pop() + st.pop())Show answer
Answer: B — CB
The stack holds A, B, C with C on top; the first pop gives C and the second gives B, so the sum is CB. "AB" and "BA" take elements from the bottom.Assertion (A): A stack is suitable for implementing the undo feature of an editor.
Reason (R): The most recent action is the first one to be reversed, which matches last-in first-out order.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
The latest action is undone first, which is LIFO, as R states. Option 2 is wrong.Consider the following statements about a stack:
A. Insertion and deletion take place at one end called the top.
B. push adds an element at the top.
C. peek removes the top element.
D. isEmpty reports whether the stack has no elements.
Choose the correct answer:Show answer
Answer: A — A, B and D only
A, B and D are correct. C is false because peek only reads the top, so option 4 is the trap.Match List I with List II:
List I:
A. push;
B. pop;
C. peek;
D. isEmpty
List II:
1. Checks for no elements;
2. Reads the top element;
3. Removes the top element;
4. Adds an element at the topShow answer
Answer: A — A-4, B-3, C-2, D-1
push adds (4), pop removes (3), peek reads (2) and isEmpty checks (1). Option 2 swaps push and pop.The value of the postfix expression 5 3 + 2 * is:
Show answer
Answer: A — 16
5 3 + gives 8 and 8 2 * gives 16. 11 results from 5 + 3 * 2 evaluated by precedence, which is a different expression.What is the output of the following code?
def ok(s):st = []for ch in s:if ch == "(":st.append(ch)elif ch == ")":if not st:return Falsest.pop()return not stprint(ok("(()"), ok("()()"))Show answer
Answer: B — False True
"(()" leaves one unmatched "(" on the stack so it is False, whereas "()()" balances completely and is True, giving False True. "True True" overlooks the leftover opening bracket.The value of the postfix expression 8 2 / 3 - 4 2 * + is:
Show answer
Answer: A — 9
8 2 / is 4, 4 3 - is 1, 4 2 * is 8 and 1 8 + is 9. 1 forgets the second part of the expression.The postfix form of A + B * C - D is:
Show answer
Answer: A — A B C * + D -
B * C comes first, then A is added and D subtracted, giving A B C * + D -. A B + C * D - would be the postfix of (A + B) * C - D.What is the output of the following code?
st = []for t in "6 3 2 * +".split():if t.isdigit():st.append(int(t))else:b, a = st.pop(), st.pop()st.append(a + b if t == "+" else a * b)print(st[0])Show answer
Answer: B — 12
3 2 * gives 6, leaving 6 and 6, and the final + gives 12. 36 multiplies instead of adding, and 18 adds 6 + 3 + 2 + ... wrongly.Assertion (A): A stack is suitable for checking balanced brackets in an expression.
Reason (R): Each closing bracket must match the most recently opened one, which is exactly the element on top of the stack.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
The latest opened bracket must be closed first, which is LIFO, as R states. Option 2 is wrong.What is the output of the following code?
s = [5]s.append(s.pop() * 2)s.append(s[-1] + 1)print(s)Show answer
Answer: A — [10, 11]
The first line pops 5 and pushes 10; the next pushes 10 + 1 = 11, leaving [10, 11]. "[11]" removes 10 and "[5, 10, 11]" forgets the first pop.