Bird
0
0

Identify the bug in this polymorphic function:

medium📝 Debug Q7 of 15
Python - Polymorphism and Dynamic Behavior

Identify the bug in this polymorphic function:

def combine(a, b):
    if isinstance(a, list) and isinstance(b, list):
        return a + b
    elif isinstance(a, dict) and isinstance(b, dict):
        return {**a, **b}
    else:
        return a.append(b)

ALists cannot be added with + operator
Bappend modifies list in place and returns None, causing unexpected output
CCannot use ** to merge dictionaries
DFunction lacks return statement in else
Step-by-Step Solution
Solution:
  1. Step 1: Understand list append behavior

    append() changes list but returns None, so returning a.append(b) returns None.
  2. Step 2: Check other parts

    Using + for lists and ** for dicts is correct. Else branch returns None unexpectedly.
  3. Final Answer:

    append modifies list in place and returns None, causing unexpected output -> Option B
  4. Quick Check:

    append returns None, so returning it causes bugs [OK]
Quick Trick: append returns None; don't return it directly [OK]
Common Mistakes:
  • Returning append() result instead of list
  • Thinking ** cannot merge dicts
  • Confusing list addition with append

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes