LearnFrenzy
Sign in Take a free test

Python Programming interview · Set 19 of 19

Python Output-Based and Tricky Questions

  • 7 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Gotchas that cause real bugs

Output questions test whether you truly understand names, mutability, scope and evaluation order. Explain the rule behind each answer — that is what earns the marks.

  • MutabilityDefaults, list multiplication and shared attributes.
  • ScopeLate binding and closures.
  • EvaluationChained comparisons, finally and identity.

Written tests and quick-fire rounds love “what will this print?” questions. Each one below hides a real Python behaviour that also causes production bugs, so understanding the explanation is worth more than memorising the answer.

1. What does this print? (mutable default argument)

[1] then [1, 2]. The default list is created once, when the function is defined, and shared by every call that uses the default. Fix: default to None and create the list inside.

def add(x, items=[]):
    items.append(x)
    return items

print(add(1))
print(add(2))

2. What does this print? (list multiplication)

[['X', 0], ['X', 0], ['X', 0]]. [[0, 0]] * 3 creates three references to the same inner list. Use a comprehension to create separate rows.

board = [[0, 0]] * 3
board[0][0] = "X"
print(board)

board = [[0, 0] for _ in range(3)]   # correct: three separate lists

3. What does this print? (late binding in lambdas)

[2, 2, 2]. Each lambda looks up i when it is called, after the loop has finished. Bind the current value with a default argument: lambda i=i: i.

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])

4. What does this print? (finally and return)

finally. A return in finally overrides the earlier return — and would even swallow an exception. Never return from finally (Python 3.14 warns about it).

def check():
    try:
        return "try"
    finally:
        return "finally"

print(check())

5. What does this print? (chained comparisons)

True then False. Python chains comparisons: 1 < 2 < 3 means 1 < 2 and 2 < 3. The same rule applies to the second line: 1 < 2 == True means 1 < 2 and 2 == True, and 2 == True is False because True equals 1. Add brackets when you mean something else.

print(1 < 2 < 3)
print(1 < 2 == True)

6. What does this print? (is vs == with integers)

True, False, True in CPython. Small integers (−5 to 256) are cached, so the first is is True; 1000 built at runtime gives two objects. The values are equal either way — use == for values.

a, b = 100, 100
x, y = int("1000"), int("1000")
print(a is b)
print(x is y)
print(x == y)

7. What does this print? (modifying a list while iterating)

[1, 3, 5] — but by accident. Removing an item shifts the rest left, so the loop skips the next element. With [2, 4, 6] it would print [4]. Build a new list or iterate over a copy.

nums = [1, 2, 3, 4, 5]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)

nums = [n for n in nums if n % 2]   # safe way

8. What does this print? (class attribute shared through instances)

It prints 1 ['a'] and then 0. Augmented assignment on an immutable class attribute (count += 1) creates an instance attribute, so the class value stays 0; but append mutates the shared list.

class C:
    count = 0
    tags = []

c = C()
c.count += 1
c.tags.append("a")
print(c.count, C.tags)
print(C.count)

Remember

Key points

  • Defaults are evaluated once

    Use None for mutable defaults.

  • [[0]] * n shares rows

    Use a comprehension.

  • Closures look up names late

    Bind values with default arguments.

  • Never remove while iterating

    Filter into a new list.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What does print(0.1 + 0.2 == 0.3) print and why? Basic

    False — binary floating point cannot represent 0.1 exactly. Use math.isclose(), or decimal.Decimal for money.

  2. 2 What is the output of print(bool([]), bool([0]), bool(""), bool(" "))? Basic

    False True False True — empty containers and strings are falsy; non-empty ones (even containing 0 or a space) are truthy.

  3. 3 What does print(round(2.5), round(3.5)) print? Intermediate

    2 4 — Python uses banker's rounding (round half to even) to reduce bias.

  4. 4 What does print(-7 // 2, -7 % 2) print? Intermediate

    -4 1 — floor division rounds towards negative infinity, and the remainder takes the sign of the divisor.

  5. 5 What is printed by a = [1, 2, 3]; b = a; a = a + [4]; print(b)? Intermediate

    [1, 2, 3] — a + [4] creates a new list and rebinds a. With a += [4], the list is mutated in place and b would show [1, 2, 3, 4].

  6. 6 What does print("abc" * 0, [1] * -1) print? Basic

    An empty string and an empty list — multiplying a sequence by zero or a negative number gives an empty sequence.

  7. 7 What does sorted("Banana") return? Basic

    ['B', 'a', 'a', 'a', 'n', 'n'] — uppercase letters sort before lowercase in Unicode order. Use key=str.lower for case-insensitive sorting.

Preparing with friends?

Share this page with your study group or placement batch.

Popular