SyntaxPilot
Courses/Python Coding Questions/Lesson 30
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Python Coding Questions · Lesson 30 of 30

Tricky output questions (interview round)

is vs ==small-int caching0.1 + 0.2mutable default argslist * n aliasinglate bindingchained comparisonstry/finally return

These are the notes for Python Coding Questions, episode 30, the last episode of the series: the interviewer's favourite round, "what does this code print?". Each program is only a few lines, but each one hides a rule of Python, and the obvious guess is wrong. We guess, run the code for real, and when the guess fails, name the rule and write the fix.

Every program was run with Python 3.13 (python3 main.py), the SyntaxPilot compiler's Python command. Every output below is real.

Words for today:

  • Object: every value in Python (a number, a string, a list) is an object in memory.
  • Identity: which object a name points to. id(x) returns a number that identifies the object; two names with the same id point to the same object.
  • == (equality): asks "do these have the same value?"
  • is (identity check): asks "are these the very same object?"
  • Small-integer cache: CPython keeps one shared object for each integer from -5 to 256, so every 7 is the same object.
  • CPython: the standard Python interpreter (the one you download from python.org).
  • Literal: a value written directly in code, like 300 or "milk".
  • Float: a number with a decimal point, stored in binary (base 2), so most decimals are stored as a close approximation.
  • Decimal: a type from the decimal module that stores decimal numbers exactly, as you write them.
  • Default argument: the value a parameter gets when the caller leaves it out: def f(cart=[]).
  • Mutable / immutable: a mutable object can change in place (list, dict, set); an immutable one cannot (int, float, str, tuple).
  • Reference: what a variable or a list slot really holds: an arrow to an object, not the object itself.
  • Aliasing: two names (or two list slots) referring to the same object.
  • List comprehension: [expr for x in items], builds a new list by running expr once per item.
  • Closure / lambda: a lambda is a small unnamed function; a closure is a function that uses a variable from the code around it.
  • Late binding: a closure looks up the variable's value when it is called, not when it is made.
  • Chained comparison: a < b < c, which Python reads as a < b and b < c.
  • finally: the block after try that always runs: after success, after an exception, even after return.

How to answer an output question

Step What to do Example
1 Read it line by line, the way the interpreter runs it don't jump to the print
2 Say your guess out loud, and why "I think True, because both are 300"
3 Name the rule underneath, in one line "is checks identity, not value"
4 Give the fix you'd write in real code "use ==; keep is for None"

The rule plus the fix is what gets the marks.

Q1: Same value, or same object?

is vs ==: the bank token

Real-life example: at a bank, the screen shows the token being called: 300. Your slip says 300. Same number, but a different piece of paper. A developer checked it with called is mine, and it worked in testing with small tokens.

called = int(input())          # token number on the screen
mine = int(input())            # token number in my hand
print(called == mine, called is mine)
print(id(called), id(mine))

Input 7 and 7:

True True
20100864 20100864

Input 300 and 300:

True False
139957579063696 139957579063792

(The id numbers are memory addresses: yours will differ, but the pattern is the same: equal for 7, different for 300.)

Why: == compares values; is compares identity (same object, same id). CPython keeps one shared object for every small integer from -5 to 256, because they are used all the time, so every 7 is the same object and is happens to say True. 300 is outside that cache: each int() call makes a new object, so there are two objects with the same value, and is says False. Code that uses is for numbers only works by luck.

Python warns you

mine = int(input())
if mine is 300:
    print("your turn")
else:
    print("please wait")

Input 300:

main.py:2: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
  if mine is 300:
please wait

A warning doesn't stop the program, so this bug ships if nobody reads warnings.

The fix

mine = int(input())
print(mine is None, mine == 300)
if mine == 300:
    print("your turn")

Input 300:

False True
your turn

Rule: use == to compare values. Use is only for one-of-a-kind objects (singletons): x is None, x is True, x is False.

0.1 + 0.2: the cashback that doesn't add up

Real-life example: a payment app gives two cashback offers on one payment, ₹0.10 and ₹0.20. If the total is ₹0.30, it sends a thank-you SMS. Nobody gets the SMS.

cashback = 0.1 + 0.2
print(cashback)
print(cashback == 0.3)

Output:

0.30000000000000004
False

Why: this isn't a Python bug; Java, C and JavaScript print the same. Write 1/3 as a decimal: 0.3333..., it never ends, so you cut it off and it's not exact. A float is stored in binary (base 2), and in binary 0.1 never ends either. So Python stores the nearest binary value, a tiny bit off; 0.1 and 0.2 are each slightly off, and the errors add up. (Numbers like 0.5 and 0.25 are exact in binary: 0.5 + 0.25 == 0.75 is True.)

The fixes

import math
from decimal import Decimal

cashback = 0.1 + 0.2
print(math.isclose(cashback, 0.3))
print(round(cashback, 2) == 0.3)
print(Decimal(0.1))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
paise = 10 + 20                  # money in whole paise
print(paise == 30, paise / 100)

Output:

True
True
0.1000000000000000055511151231257827021181583404541015625
True
True 0.3
  • math.isclose(a, b) allows a tiny relative difference (by default 1e-09): the right way to compare floats.
  • round(x, 2) works when you know how many decimal places matter.
  • Decimal(0.1) (from a float) shows what 0.1 really is in memory, and keeps the error. Always build a Decimal from a string: Decimal("0.1").
  • For money, the simplest exact way: count in whole paise as integers, and divide by 100 only to display.

Q2: Shared by accident

Three bugs, one idea: you thought you had something new, but it was shared.

Mutable default arguments: the cart that remembers

Real-life example: a shop that keeps one basket at the door and hands it to every customer, never emptied.

def add_item(item, cart=[]):
    cart.append(item)
    return cart

print(add_item("milk"))            # Asha's order
print(add_item("bread"))           # Ravi's order, a new cart?
print(add_item.__defaults__)

Output:

['milk']
['milk', 'bread']
(['milk', 'bread'],)

Ravi got Asha's milk. add_item.__defaults__ (the tuple of the function's stored default values) shows the default list itself now holds both items.

Why: the default value is created once, when the def line runs, not on every call. Every call that leaves out cart gets that same list. It only bites with mutable defaults (list, dict, set); 0, "" or None are safe because they can't change in place.

The fix: default to None, and build a new list inside the function.

def add_item(item, cart=None):
    if cart is None:               # a new list on every call
        cart = []
    cart.append(item)
    return cart

print(add_item("milk"))            # Asha's order
print(add_item("bread"))           # Ravi's order
print(add_item("eggs", ["milk"]))  # add to an existing cart

Output:

['milk']
['bread']
['milk', 'eggs']

(And cart is None is exactly the one place where is belongs.)

[[0] * 3] * 3: one booking, a whole column

Real-life example: a cinema hall with 3 rows of 3 seats (0 = free). Book row 0, seat 1.

seats = [[0] * 3] * 3              # 3 rows of 3 seats
seats[0][1] = 1                    # book row 0, seat 1
for row in seats:
    print(row)
print(seats[0] is seats[1])

Output:

[0, 1, 0]
[0, 1, 0]
[0, 1, 0]
True

Why: a list holds references (arrows to objects), not the objects. [row] * 3 repeats the reference three times, so seats[0], seats[1] and seats[2] are three names for one list (aliasing). The inner [0] * 3 is fine: integers are immutable, so seats[0][1] = 1 puts a new object in that slot instead of changing the 0.

seats[0] ─┐
seats[1] ─┼──▶ [0, 1, 0]     (ONE list)
seats[2] ─┘

The fix: a list comprehension runs the expression once per turn, so it builds a new row each time.

seats = [[0] * 3 for _ in range(3)]   # a new row each time
seats[0][1] = 1                       # book row 0, seat 1
for row in seats:
    print(row)
print(seats[0] is seats[1])

Output:

[0, 1, 0]
[0, 0, 0]
[0, 0, 0]
False

The same trap appears with dict.fromkeys(keys, []) (see practice question 6). Building the grid is O(rows × columns) time and space either way.

Late binding: every lift button goes to floor 2

Real-life example: lift buttons that don't remember their own floor. They read a board when you press them, and the board shows the last floor written.

buttons = []
for floor in range(3):
    buttons.append(lambda: print("going to floor", floor))

for press in buttons:
    press()

Output:

going to floor 2
going to floor 2
going to floor 2

Why: the lambda doesn't save the value of floor when it is made. It saves the name floor, and looks it up when it is called. By then the loop has finished and floor is 2. This is late binding.

The fix uses the rule from the cart: defaults are made once, when the function is made. So floor=floor as a default saves the floor of each turn of the loop.

buttons = []
for floor in range(3):
    buttons.append(lambda floor=floor: print("going to floor", floor))

for press in buttons:
    press()

Output:

going to floor 0
going to floor 1
going to floor 2

(functools.partial(print, "going to floor", floor) is another clean fix.)

The one question that solves all three

Bug What is shared
def f(cart=[]) one list object, shared by every call
[[0] * 3] * 3 one row, shared by three names
lambda: floor in a loop one variable, read when called

In every output question ask: is this a new object, or a new name for an old one?

Q3: Control-flow surprises

Chained comparisons

Real-life example: an amusement park ride for ages 12 to 60: 12 <= age <= 60, just like maths.

Python reads a chain as comparisons joined by and: a < b < c means a < b and b < c (and b is evaluated only once). Brackets change the meaning: (3 > 2) > 1 first gives True, then compares True > 1; in a comparison True counts as 1 and False as 0. Every comparison operator chains, including ==, in and is.

age = 15
print(12 <= age <= 60)             # the ride's age limit
print(3 > 2 > 1)
print((3 > 2) > 1)
print(False == False in [False])
print((False == False) in [False])

Output:

True
True
False
True
False
  • 3 > 2 > 1 → 3 > 2 and 2 > 1 → True.
  • (3 > 2) > 1 → True > 1 → 1 > 1 → False.
  • False == False in [False] → False == False and False in [False] → True and True → True.
  • (False == False) in [False] → True in [False] → False.

Rule: chain simple ranges like the age check; if a chain mixes operators, add brackets.

A return inside finally: the ATM

Real-life example: an ATM: withdraw ₹100 → cash; over ₹500 → declined. Whatever happens, the card must come back: that's what finally is for. But the developer also put a return inside finally.

def withdraw(amount):
    try:
        if amount > 500:
            raise ValueError("over the limit")
        return "cash"
    except ValueError:
        return "declined"
    finally:
        print("card returned")
        return "done"

print(withdraw(100))
print(withdraw(900))

Output:

card returned
done
card returned
done

Why: return "cash" doesn't leave right away: Python first runs finally, and finally's own return replaces the answer. The last return wins.

It's worse: a return in finally also throws away an exception on its way out.

def withdraw(amount):
    try:
        print(100 / amount)
    finally:
        return "done"              # hides the crash

print(withdraw(0))

Output:

done

The ZeroDivisionError vanished without a trace. This is such a common bug that Python 3.14 prints a SyntaxWarning for return, break or continue inside finally (PEP 765). Python 3.13, used here, stays silent.

The fix: finally is for cleanup only (close the file, return the card, write the log). Never return from it.

def withdraw(amount):
    try:
        if amount > 500:
            raise ValueError("over the limit")
        return "cash"
    except ValueError:
        return "declined"
    finally:
        print("card returned")     # cleanup only, no return

print(withdraw(100))
print(withdraw(900))
print(withdraw("ten"))

Output:

card returned
cash
card returned
declined
card returned
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    print(withdraw("ten"))
          ~~~~~~~~^^^^^^^
  File "main.py", line 3, in withdraw
    if amount > 500:
       ^^^^^^^^^^^^
TypeError: '>' not supported between instances of 'str' and 'int'

The card came back every time, and the real error reached us so we can fix it.

Common mistakes (and what you really see)

Mistake What you see Why Fix
if mine is 300: SyntaxWarning: "is" with 'int' literal. Did you mean "=="? and a wrong branch is checks identity == for values, is only for None
a is b for numbers from input() True for 7, False for 300 small-int cache -5..256 ==
0.1 + 0.2 == 0.3 False (0.30000000000000004) binary floats are approximate math.isclose, round, Decimal("0.1"), paise
Decimal(0.1) 0.1000000000000000055511151231257827021181583404541015625 built from the float, error included Decimal("0.1")
def f(cart=[]) the last call's items appear default made once at def cart=None, then cart = []
[[0] * 3] * 3 one booking fills a whole column 3 references, 1 row [[0] * 3 for _ in range(3)]
dict.fromkeys(keys, []) every key shares one list one default object {k: [] for k in keys}
lambda: print(floor) in a loop every button: floor 2 late binding lambda floor=floor: ...
(3 > 2) > 1 thinking it's a chain False True > 1 is 1 > 1 no brackets, or write and
return inside finally always "done", exceptions vanish the last return wins finally only cleans up

Your turn (solutions)

1. print(round(2.5), round(3.5))

2.

a = b = []
a.append(1)
print(b)

3. t = ([1], 2) then t[0] += [3]. What happens to t?

Solutions
print(round(2.5), round(3.5))
a = b = []
a.append(1)
print(b)
t = ([1], 2)
try:
    t[0] += [3]
except TypeError as e:
    print("TypeError:", e)
print(t)

Output:

2 4
[1]
TypeError: 'tuple' object does not support item assignment
([1, 3], 2)
  1. 2 4. Python's round uses banker's rounding (round half to even): a value exactly halfway goes to the nearest even number, so 2.5 → 2 and 3.5 → 4. This avoids always rounding up, which would bias totals.
  2. [1]. a = b = [] makes one list with two names (aliasing), so appending through a shows through b. Fix: a, b = [], [].
  3. Both: it raises and it changes. t[0] += [3] is two steps: t[0].__iadd__([3]) extends the list in place (it's mutable, so this works), then Python tries t[0] = <that list>, and a tuple can't be assigned to: TypeError. The list was already changed, so t is ([1, 3], 2). Fix: t[0].append(3) or t[0].extend([3]), which never assigns to the tuple.

Mini project: fix a buggy billing module

A small chai stall's billing code has three of today's traps in it. Spot them before you read on.

def new_bill(item, items=[]):
    items.append(item)
    return items

def pay(total):
    try:
        if total == 0.3:
            return "thank you SMS"
        return "paid"
    finally:
        return "logged"

asha = new_bill("chai")
ravi = new_bill("samosa")
print(asha, ravi)
print(pay(0.1 + 0.2))

Output:

['chai', 'samosa'] ['chai', 'samosa']
logged

Bugs: (1) a mutable default list shares one bill between Asha and Ravi; (2) total == 0.3 compares floats exactly; (3) return "logged" in finally overrides every answer.

Fixed version
import math

def new_bill(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

def pay(total):
    try:
        if math.isclose(total, 0.3):
            return "thank you SMS"
        return "paid"
    finally:
        print("logged")             # cleanup only

asha = new_bill("chai")
ravi = new_bill("samosa")
print(asha, ravi)
print(pay(0.1 + 0.2))
print(pay(0.5))

Output:

['chai'] ['samosa']
logged
thank you SMS
logged
paid

In a real billing system, store money as whole paise (int) or Decimal("...") instead of floats.

Practice questions (with solutions)

1. What does this print?

x = [1, 2, 3]
y = x
y += [4]
print(x)
y = y + [5]
print(x, y)
Solution
[1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4, 5]

y = x makes an alias. += on a list changes it in place, so x sees the 4. y = y + [5] builds a new list and points y at it, so x is unchanged.

2. print(0.1 * 3 == 0.3, 0.5 + 0.25 == 0.75)

Solution
False True

0.1 can't be stored exactly in binary; 0.5 (1/2) and 0.25 (1/4) can, so their sum is exact.

3. What does this print, and how do you fix it?

funcs = [lambda x: x * i for i in range(3)]
print([f(10) for f in funcs])
Solution
funcs = [lambda x: x * i for i in range(3)]
print([f(10) for f in funcs])
funcs = [lambda x, i=i: x * i for i in range(3)]
print([f(10) for f in funcs])

Output:

[20, 20, 20]
[0, 10, 20]

Late binding again: every lambda reads i when called, and by then i is 2. A default i=i captures each value.

4. What does this print?

def f():
    try:
        return 1
    finally:
        print("bye")

print(f())
Solution
bye
1

finally runs before the function hands back its value, so bye is printed first. With no return in finally, the 1 survives.

5. What does this print?

print(1 < 2 > 1.5 == 1.5)
print(5 > 3 == True)
Solution
True
False

1 < 2 and 2 > 1.5 and 1.5 == 1.5 → True. 5 > 3 == True is a chain: 5 > 3 and 3 == True → True and False → False (True equals 1, not 3).

6. What does this print, and what's the fix?

d = dict.fromkeys(["asha", "ravi"], [])
d["asha"].append("milk")
print(d)
Solution
d = dict.fromkeys(["asha", "ravi"], [])
d["asha"].append("milk")
print(d)
d = {name: [] for name in ["asha", "ravi"]}
d["asha"].append("milk")
print(d)

Output:

{'asha': ['milk'], 'ravi': ['milk']}
{'asha': ['milk'], 'ravi': []}

fromkeys puts the same list under every key. A dict comprehension makes a new list for each key.

Quick quiz

What does this print?

def visit(name, seen=[]):
    seen.append(name)
    return len(seen)

print(visit("asha"), visit("ravi"), visit("neha"))

(A) 1 1 1 (B) 1 2 3 (C) 3 3 3 (D) TypeError

Answer

(B) 1 2 3. seen=[] is made once, when def runs. Every call appends to the same list, so its length grows: 1, then 2, then 3. (The three calls run left to right before print joins their results.)

Interview questions

  1. Difference between is and ==? == compares values (it calls __eq__); is compares identity (same object, same id). Use is only for singletons like None.
  2. Why is 256 is 256 true but two 300s from input() not? CPython caches small integers from -5 to 256; larger ones are new objects each time. It's an implementation detail, never something to rely on.
  3. Why is 0.1 + 0.2 != 0.3? Floats are binary (IEEE 754 double precision); 0.1 has no exact binary form, so tiny errors add up. Compare with math.isclose and use Decimal or integer paise for money.
  4. What's wrong with def f(x=[])? The default is evaluated once at definition time and shared by every call. Use None and create the list inside.
  5. Why does [[0] * 3] * 3 behave strangely? * repeats references, so all rows are one list. Use a list comprehension.
  6. What is late binding in closures? A closure looks up free variables when called, not when defined. Capture values with a default argument or functools.partial.
  7. How does Python evaluate a < b < c? As a < b and b < c, with b evaluated once; it short-circuits if a < b is false.
  8. What happens if finally contains return? It overrides any earlier return and discards an in-flight exception. Python 3.14 warns about it (PEP 765). Keep finally for cleanup.
  9. Is round(2.5) 3? No, 2: Python rounds halves to the nearest even number (banker's rounding).
  10. Why does t[0] += [3] on a tuple both fail and succeed? The list is extended in place first, then assigning back into the tuple raises TypeError.

Glossary

Term Meaning Example
Object A value in memory 300, [0, 0, 0]
Identity / id() Which object a name points to id(mine)
== Same value? 300 == 300 → True
is Same object? x is None
Singleton An object of which only one exists None, True, False
Small-integer cache CPython's shared objects for -5..256 every 7 is one object
CPython The standard Python interpreter python.org's Python
Literal A value written directly in code 300, "milk"
SyntaxWarning A warning when code is compiled; the program still runs "is" with 'int' literal
Float A binary number with a decimal point 0.1
Binary (base 2) Numbers written with only 0 and 1 0.1 never ends in binary
math.isclose Compares floats with a small tolerance isclose(0.1 + 0.2, 0.3)
Decimal Exact decimal numbers (from the decimal module) Decimal("0.1")
Paise Whole-number money units (100 paise = ₹1) 30 paise = ₹0.30
Default argument A parameter's value when it's left out cart=None
__defaults__ A function's stored default values (['milk', 'bread'],)
Mutable / immutable Can / can't change in place list / int
Reference An arrow from a name or slot to an object seats[0] → the row
Aliasing Two names for one object a = b = []
List comprehension Builds a new list, one item per turn [[0] * 3 for _ in range(3)]
lambda A small unnamed function lambda: print(floor)
Closure A function that uses variables from around it the lift buttons
Late binding A closure reads a variable when called every button → floor 2
Chained comparison a < b < c = a < b and b < c 12 <= age <= 60
try / except / finally Run, handle errors, always clean up the ATM returns the card
Exception An error raised while the program runs ZeroDivisionError, TypeError
Banker's rounding Halves round to the nearest even number round(2.5) → 2

Summary

  • is vs ==: == is value, is is identity. Small ints (-5..256) are cached, so is only looks right by luck. Use is only for None.
  • 0.1 + 0.2: floats are binary approximations. Compare with math.isclose; keep money in Decimal("...") or whole paise.
  • Mutable defaults: made once at def; use None and build inside.
  • [[0] * 3] * 3: three references to one row; use a list comprehension.
  • Late binding: lambdas read variables when called; capture with x=x.
  • Chains: a < b < c means a < b and b < c; brackets change the meaning; True is 1.
  • finally: always runs; never return from it, or it overrides answers and hides exceptions.
  • Ask every time: is this a new object, or a new name for an old one?

That's the end of Python Coding Questions: 30 episodes from the basics to the interview round. Revise the playlist a few questions a day, without looking at the notes, and you're ready for a Python coding round.