GATE DA’s code questions are short Python snippets with one question: what does this print? They’re won or lost on a handful of exact behaviours: aliasing versus copying, set operations, simultaneous assignment, / versus //, mutable default arguments, closures and recursion. This part teaches you to trace code the way the interpreter does, one line at a time, with a tracer that shows every variable as it changes.
You need: nothing beyond basic programming familiarity. If you’ve never written Python, read slowly and use the tracer on every example.
Values, lists, sets and loops: what the interpreter really does
In Python a variable is a name attached to an object, so two names can point to the same list, and changing it through one name changes what the other sees.
Code-tracing questions carry 4–7 marks a year and the share is growing. Most mistakes come from a few behaviours (aliasing, set algebra, simultaneous assignment, integer versus float division) that this chapter makes precise.
It’s like two scorers sharing one scorebook: if one writes in it, the other sees the change, because there’s only one book. Making a photocopy is what A[:] does.
“What does this print?” questions every year, plus list-method questions.
| Type | Example | Mutable? | Remember |
|---|---|---|---|
int, float | 7, 3.5 | no | 7 / 2 = 3.5 (always float), 7 // 2 = 3, 7 % 2 = 1 |
str | "six" | no | indexing and slicing like lists |
list | [1, 2, 3] | yes | ordered; append(x) adds one item, extend(L) adds each item of L |
tuple | (1, 2) | no | like a list you can’t change |
dict | {"runs": 45} | yes | key → value; k in d checks keys |
set | {"a", "b"} | yes | no duplicates, no order; | union, & intersection, - difference |
- Aliasing:
B = Amakes B another name for the same list.A[:]orlist(A)makes a copy. - Simultaneous assignment: in
A, B = B, A(orA,B,C = A-B, B-C, C-A) the whole right side is evaluated first, using the old values, and only then assigned. - Division:
/always gives a float ((15-1)/2is7.0);//is integer division. - Slicing
a[i:j]includes index i and excludes j;a[::-1]reverses;a[-1]is the last item.range(1, 11)is 1 to 10. - Loops:
continueskips to the next iteration;breakleaves the loop, and the loop variable keeps its last value.
Step through each program one line at a time. The highlighted line is about to run; the box on the right shows every variable’s current value. In “Aliasing”, watch B change when only B is touched, and C stay separate. Then step through GATE 2025 Q47 and watch the simultaneous assignments use the old values.
Consider the following Python code snippet.
A={"this","that"}
B={"that","other"}
C={"other","this"}
while "other" in C:
if "this" in A:
A,B,C=A-B,B-C,C-A
if "that" in B:
A,B,C=C|A,A|B,B|C
When the above program is executed, at the end, which of the following sets contains “this”?
- Only A
- Only B
- Only C
- A, C
Iteration 1, first
if(“this” in A): with the old values, A−B = {this}, B−C = {that}, C−A = {other}. Now A = {this}, B = {that}, C = {other}.All three differences use the values from before this line. Updating A first and then using the new A would give a different answer.
Second
if(“that” in B, true): C|A = {other, this}, A|B = {this, that}, B|C = {that, other}. Now A = {other, this}, B = {this, that}, C = {that, other}.Again, all right-hand sides first.
C still contains “other”, so loop again. First
if(“this” in A, true): A−B = {other}, B−C = {this}, C−A = {that}. Secondif: “that” in B = {this}? No.Check each condition against the current values.
Now C = {that} has no “other”: the loop ends with A = {other}, B = {this}, C = {that}. Only B contains “this”: (B).
The tracer above shows exactly these states. Official key: (B).
Consider the following Python declarations of two lists. A=[1,2,3] B=[4,5,6]. Which one of the following statements results in A= [1, 2, 3, 4, 5, 6]?
A.extend(B)A.append(B)A.update(B)A.insert(B)
One of these adds B as a single item; one isn’t a list method at all.
extend adds each element of B. append(B) would give [1, 2, 3, [4, 5, 6]]. Lists have no update (that’s for sets and dicts), and insert needs an index and a value. Official key: (A).
What is the output of the following python program?
i=1
j=1
for i in range(1, 11):
if i % 3 != 0:
j += 2
continue
if j % 3 == 0:
break
print(i + j)Track (i, j). For i not divisible by 3, j grows by 2 and the rest is skipped. At i = 3, 6, 9, check whether j is divisible by 3.
i = 1, 2: j becomes 3, 5. i = 3: j = 5, not divisible by 3, so no break. i = 4, 5: j becomes 7, 9. i = 6: j = 9 is divisible by 3, so break with i = 6. Output $6 + 9 = 15$. (Sample paper, no official key; verified by running it.)
With a = [10, 20, 30, 40, 50], what are sum(a[1:4]) and a[::-1][0]?
a[1:4] is indices 1, 2, 3. a[::-1] is the reversed list.
a[1:4] = [20, 30, 40], sum 90. Reversed list starts with 50.
What does this print?
A = [1, 2, 3] B = A B.append(4) print(A)
Is B a copy of A, or another name for the same list?
[1, 2, 3, 4]: B and A are the same list object.
What does this program print?
a = [3, 1, 4, 1, 5, 9, 2, 6] b = a c = a[:] b[2:5] = [0] c.append(b.pop()) a += c[-3:] print(len(a) + sum(a))
Decide first which names point to the same list and which hold a copy. Then remember that a slice assignment can change the length of a list, and that += on a list changes it in place.
b = a makes b a second name for the same list; c = a[:] is a separate copy, [3, 1, 4, 1, 5, 9, 2, 6].
b[2:5] = [0] replaces the three items at indices 2, 3, 4 (4, 1, 5) by the single item 0, so the shared list becomes [3, 1, 0, 9, 2, 6]. The copy c is untouched.
b.pop() removes 6 from the shared list, leaving [3, 1, 0, 9, 2], and c.append(6) gives c = [3, 1, 4, 1, 5, 9, 2, 6, 6].
c[-3:] is [2, 6, 6], and a += … extends the shared list: a = [3, 1, 0, 9, 2, 2, 6, 6].
Length 8, sum 3 + 1 + 0 + 9 + 2 + 2 + 6 + 6 = 29. The program prints 8 + 29 = 37.
What does this program print?
words = ["kern", "heur", "back",
"kern", "neur", "back",
"kern"]
d = {}
for w in words:
d[w] = d.get(w, 0) + 1
if d[w] == 2:
d[w[::-1]] = d[w]
print(len(d), sum(d.values()))- 4 7
- 6 12
- 6 11
- Nothing: it stops with a
KeyError
Keep a table of the dictionary after each word. When a count reaches 2, a second key is added: what is its value, and does it change later?
d.get(w, 0) returns 0 for a new key, so no KeyError can occur.
Counting: kern → 1, heur → 1, back → 1. The second “kern” makes kern 2, so d["nrek"] = 2. “neur” → 1. The second “back” makes back 2, so d["kcab"] = 2. The third “kern” makes kern 3; the test d[w] == 2 is false, so nothing else happens.
d["nrek"] received the integer 2 at that moment. Integers are immutable, so it stays 2 when kern later becomes 3.
Final dictionary: kern 3, heur 1, back 2, nrek 2, neur 1, kcab 2. That is 6 keys with values summing to 11. Answer (C).
(A) ignores the reversed keys; (B) assumes nrek follows kern up to 3.
Consider the following code.
R = [[0] * 3] * 3 S = [[0] * 3 for _ in range(3)] R[0][1] = 5 S[0][1] = 5 T = R[:] T[2] = [7, 7, 7] T[1][0] = 1
After it runs, which of the following is/are correct?
sum(map(sum, R))is 18sum(map(sum, S))is 15T[2]is[7, 7, 7]whileR[2]is[1, 5, 0]R[0][0]is still 0, becauseT[1][0] = 1changes only the copyT
[row] * 3 repeats a reference to one inner list. R[:] copies the outer list only. For each line, ask whether it rebinds a slot of an outer list or changes an inner list.
R holds the same inner list three times. S builds three separate inner lists.
R[0][1] = 5 changes the one shared inner list, so every row of R reads [0, 5, 0]. S[0][1] = 5 changes only S’s first row.
T = R[:] is a new outer list whose three slots point to the same shared inner list. T[2] = [7, 7, 7] rebinds T’s third slot only; R is not affected.
T[1][0] = 1 goes through T’s second slot to the shared inner list, which becomes [1, 5, 0]. All three rows of R see it.
(A) True: R is three rows of [1, 5, 0], sum 3 × 6 = 18. (B) False: S’s sum is 5, since only one row changed. (C) True. (D) False: the copy was shallow, so R[0][0] is 1.
Correct: A, C.
- Keep a small table of variable values and update it line by line.
- For simultaneous assignment, compute every right-hand side with the old values first.
- Note when
/produces a float; it can change what gets printed.
- Treating
B = Aas a copy. - Confusing
append(adds one item) withextend(adds many). - Forgetting that
range(a, b)stops at b − 1.
- Names point to objects: B = A aliases the list, while A[:] copies it. Lists, dicts and sets are mutable.
- In A, B = X, Y the right side is evaluated fully before assigning. Sets use |, & and −.
- / gives a float and // an integer; slices exclude the end index; continue skips and break exits.
After a, b = 3, 5 then a, b = b, a + b, the values are
{1, 2, 3} - {2, 3, 4} is
^.print((15 - 1) / 2) prints
/ always gives a float.Functions, scope and recursion: the questions GATE loves to trick
A default argument is created once, when the function is defined; an inner function remembers the variables of the call that created it; and a recursive function’s work is a tree of calls you can count.
2026 alone had three questions on exactly these behaviours (Q16, Q39, Q50), and recursion-tracing questions appear every year.
It’s like a team kit bag handed down season after season: if one player leaves a bat in the shared default bag, the next player finds it there. Bring your own bag (pass an argument) and you start empty.
Every year: tracing function calls, closures, default arguments and recursive call counts.
- Arguments are passed as references to objects. If a function mutates a list argument (
lst.append), the caller sees the change. If it rebinds the name (lst = [...]), the caller doesn’t. - Default values are evaluated once, when the
defruns. A mutable default (lst=[]) is therefore shared by every call that doesn’t pass its own list. - Closures: an inner function can use variables of the enclosing function. Each call of the outer function creates fresh variables, so two closures from two calls don’t share them.
- Recursion: each call gets its own frame on the call stack with its own local variables. It returns to the caller when done.
Step through each program. In “2026 Q16”, watch lst already contain 1 when the second call starts. In “2026 Q50”, notice that f1 and f2 each carry their own x. In the recursive ones, watch the call stack grow and shrink, and read each “returning” value.
Consider the given Python program.
def append_to_lst(val, lst=[]):
lst.append(val)
return lst
print(append_to_lst(1))
print(append_to_lst(2))
print(append_to_lst(3, []))
Which of the following is the correct output of this program?
- [1] [2] [3]
- [1] [1, 2] [3]
- [1] [2] [1, 2, 3]
- [1] [1, 2] [1, 3]
When
defruns, Python creates one empty list and stores it as the default forlst.Defaults are evaluated once, at definition time, not on each call.
Call 1 uses the default list: it becomes [1], which is printed. Call 2 uses the same default list, now [1]; it becomes [1, 2], which is printed.
The default object persists between calls because it’s mutable and shared.
Call 3 passes a brand-new empty list, so it prints [3], and the default list is untouched. Output (B).
Official key: (B). (The usual fix is
lst=None, thenif lst is None: lst = []inside.)
GATE 2026 Q39 asks how many calls mystery(4) makes, where mystery(n) calls mystery(n-1) and mystery(n-2) until $n \le 0$. Each dot is one call; orange dots are base cases. Change $n$ and watch the count grow almost as fast as the Fibonacci numbers.
Consider the given Python program.
def outer():
x = []
def inner(val):
x.append(val)
return x
return inner
f1 = outer()
f2 = outer()
print(f1(10)) # Line P
print(f1(20)) # Line Q
print(f2(30)) # Line R
print(f1(40)) # Line SWhich of the following options is/are correct?
- f1 and f2 share the same list x
- Output of Line Q is [10, 20]
- Output of Line R is [10, 20, 30]
- Output of Line S is [10, 20, 40]
Each call to outer() runs x = [] afresh. Which list does each closure hold?
f1 and f2 come from separate calls, so each has its own x: (A) ✗. f1’s list: [10], then [10, 20] at Line Q ✓, then [10, 20, 40] at Line S ✓. f2’s list is [30] at Line R ✗. Official key: B; D.
A recursive function in Python is given.
def mystery(n):
if n <= 0:
return 1
else:
return mystery(n-1) + mystery(n-2)Now, consider the following function call: mystery(4). Assume that a typical runtime stack is used to manage function calls. Each function call is pushed onto the stack and removed only after it finishes execution. Which of the following options denotes the total number of function calls (i.e., the total number of stack activations), including the initial call, to compute mystery(4)?
Let T(n) be the number of calls. T(n) = 1 + T(n−1) + T(n−2) for n > 0, and T(0) = T(−1) = 1.
T(0) = T(−1) = 1; T(1) = 1 + 1 + 1 = 3; T(2) = 1 + 3 + 1 = 5; T(3) = 1 + 5 + 3 = 9; T(4) = 1 + 9 + 5 = 15. Official key: (C) 15.
Consider the following Python code snippet.
def f(a,b):
if (a==0):
return b
if (a%2==1):
return 2*f((a-1)/2,b)
return b+f(a-1,b)
print(f(15,10))The value printed by the code snippet is ______ (Answer in integer)
Unwind: f(15) = 2·f(7.0), f(7.0) = 2·f(3.0), f(3.0) = 2·f(1.0), f(1.0) = 2·f(0.0). Note that 7.0 % 2 == 1 is still true for floats.
f(0.0, 10) = 10, so f(1.0) = 20, f(3.0) = 40, f(7.0) = 80, f(15) = 160. The / makes the arguments floats, but the arithmetic is unaffected, and the final value is the integer 2·80 = 160. Official key: 160.
Consider the following Python code:
def count(child_dict, i):
if i not in child_dict.keys():
return 1
ans = 1
for j in child_dict[i]:
ans += count(child_dict, j)
return ans
child_dict = dict()
child_dict[0] = [1,2]
child_dict[1] = [3,4,5]
child_dict[2] = [6,7,8]
print(count(child_dict,0))Which ONE of the following is the output of this code?
child_dict describes a tree: 0 has children 1, 2; 1 has 3, 4, 5; 2 has 6, 7, 8. What does count add up?
count returns 1 for a leaf and 1 + (sum over children) otherwise: it counts nodes in the subtree. Nodes 0–8: 9. Official key: (D) 9.
What does this program print?
def collect(n, acc=[]):
if n == 0:
return acc
acc.append(n)
return collect(n - 1, acc)
x = collect(3)
y = collect(2)
z = collect(2, [])
print(len(x) + len(y) + len(z))The recursive calls pass acc along explicitly, but the first call of each top-level line may not. Which list does each of x, y and z name when the last line runs?
The default list is created once, when def runs. Call it D.
collect(3) uses D and passes D down the recursion: D becomes [3, 2, 1], and x names D.
collect(2) also uses D, which now becomes [3, 2, 1, 2, 1]; y names D too, so x and y are the same list.
collect(2, []) uses a fresh list: z = [2, 1].
When the print runs, len(x) = len(y) = 5 and len(z) = 2: total 12. (Treating every call as fresh gives 7; taking a snapshot of x after the first call gives 10.)
What does this program print?
fs = [lambda x: x + i for i in range(3)] print(sum(f(10) for f in fs))
- 30
- 33
- 36
- Nothing: it stops with a
NameError, becauseino longer exists
A lambda’s body runs only when the lambda is called. At that moment, which value of i does it find?
Each lambda is a closure over the comprehension’s variable i. It does not copy the value of i when it is created; it looks i up when it is called.
The three lambdas are called only in the last line, after the comprehension has finished with i = 2. The variable still exists for them, because the closures keep it alive, so there is no NameError.
Each call returns 10 + 2 = 12, and the sum is 3 × 12 = 36. Answer (C).
(B) 33 = 10 + 11 + 12 is what you get if each lambda fixes its own i, for example with lambda x, i=i: x + i: a default value is evaluated when the lambda is created.
What are the two values this program prints?
calls = 0
def g(n):
global calls
calls += 1
if n <= 1:
return n
return g(n // 2) + g(n // 3)
v = g(12)
print(v, calls)Work bottom-up. Find g(0), g(1), g(2), g(3), g(4) and g(6) first, and alongside each one the number of calls it makes, including itself.
Values: g(0) = 0 and g(1) = 1. Then g(2) = g(1) + g(0) = 1, g(3) = g(1) + g(1) = 2, g(4) = g(2) + g(1) = 2, g(6) = g(3) + g(2) = 3, and g(12) = g(6) + g(4) = 5.
Calls: let C(n) be the number of calls made by g(n), itself included. C(0) = C(1) = 1 and C(n) = 1 + C(n // 2) + C(n // 3).
C(2) = 1 + 1 + 1 = 3, C(3) = 1 + 1 + 1 = 3, C(4) = 1 + C(2) + C(1) = 5, C(6) = 1 + C(3) + C(2) = 7, C(12) = 1 + C(6) + C(4) = 13.
The program prints 5 13.
- Write each recursive call as a node in a tree and fill in return values bottom-up.
- For call counts, set up the recurrence T(n) = 1 + (calls made by the children).
- Ask “when was this object created?” for every default argument and closure variable.
- Assuming a default list starts empty on every call.
- Assuming two closures from separate calls share variables.
- Forgetting the initial call when counting calls.
- Default arguments are created once at definition time: a mutable default is shared across calls.
- Each call of an outer function creates fresh local variables, so closures from different calls don’t share them.
- Recursion forms a call tree; count calls with T(n) = 1 + Σ T(children) and evaluate return values from the leaves up.
GATE 2024 Q41: fun(D, s1, s2) swaps D[s1] and D[s2], then calls fun(D, s1+1, s2-1) while s1 < s2. It
A function receives a list L and runs L = L + [99]. In the caller, the original list
L + [99] builds a new list, and L = just rebinds the local name.L.append(99) would.)Using T(n) = 1 + T(n−1) + T(n−2) with T(0) = T(−1) = 1, the number of calls made by mystery(5) is
After x = [1, 2]; y = x[:]; y.append(3), what is x?
x[:] made a copy, so y is a separate list.y = x.A function with a default d={} adds a key on each call (without passing d). After three calls, the default dict holds
sum(range(1, 5)) // 3 evaluates to
// is integer division.range(1, 5) stops at 4.