Practice: Python Conceptual Interview Questions
Q1. Identity versus equality
Write code that creates two equal lists and prints whether they are equal and whether they are the same object.
Goal: Distinguish == from is.
Q2. Safe default argument
Write a function add_item(item, items=None) that returns a new list with the item when no list is given. Call it twice with 'a' and 'b' and print both results.
Goal: Avoid the mutable default trap.
Q3. Deep copy a nested list
Copy [[1, 2], [3]] with deepcopy, change the original's first inner list by appending 9, and print the copy.
Goal: Use deepcopy for nested data.
Q4. Generator of squares
Write a generator function squares(n) that yields i*i for i from 1 to n. Print list(squares(4)).
Goal: Write a simple generator.
Q5. Timing-style decorator
Write a decorator twice that calls the wrapped function two times and returns the second result. Decorate a function that prints 'hi' and returns 5, then print the returned value.
Goal: Write a decorator.
Q6. Count with a closure
Write make_counter() that returns a function; each call to it returns the next number starting at 1. Print the first three calls separated by spaces.
Goal: Use closures and nonlocal.
Q7. Alias effect
What does this print?
a = [1, 2]
b = a
b.append(3)
print(a)Goal: Understand aliasing.
Q8. String is immutable
What does this print?
s = 'cat'
t = s
t += 's'
print(s, t)Goal: Understand immutability.
Q9. Shared default list
What does this print?
def f(x, acc=[]):
acc.append(x)
return len(acc)
print(f(1), f(2), f(3))Goal: Spot the default argument trap.
Q10. Shallow copy surprise
What does this print?
a = [[0], [0]]
b = a.copy()
b[0].append(1)
print(a)Goal: Understand shallow copies.
Q11. Exhausted generator
What does this print?
g = (x for x in range(3))
print(sum(g))
print(sum(g))Goal: Know generators are single-use.
Q12. Tuple holding a list
What does this print?
t = (1, [2, 3])
t[1].append(4)
print(t)Goal: Understand tuple immutability.
Q13. Fix the default argument
This function should give a new list every call but shares one list. Fix it.
def collect(x, bucket=[]):
bucket.append(x)
return bucket
print(collect(1))
print(collect(2))Goal: Fix the mutable default bug.
Q14. Fix the None check
The check below uses the wrong operator style for None. Rewrite it with the recommended form so it prints 'missing'.
value = None
if value == None:
print('missing')Goal: Use is None.
Q15. Why does the GIL matter?
In two or three sentences, explain what the GIL is and when threads still help.
Goal: Explain the GIL.
Q16. Pass by object reference
A function does `items.append(1)` on its parameter, and another does `items = [1]`. Which one affects the caller's list and why?
Goal: Explain how arguments are passed.