Bird
Raised Fist0

Consider this polymorphic function:

hard🚀 Application Q9 of Q15
Python - Polymorphism and Dynamic Behavior

Consider this polymorphic function:

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

What is the output of combine({'x':1}, {'y':2}) and combine([1,2], [3,4])?

A{'x': 1, 'y': 2} and [1, 2, 3, 4, 5]
B{'x': 1} and [1, 2, 3, 4]
CError and [1, 2, 3, 4]
D{'x': 1, 'y': 2} and [1, 2, 3, 4]
Step-by-Step Solution
Solution:
  1. Step 1: Combine two dicts

    Using {**a, **b} merges dicts: {'x':1} and {'y':2} become {'x':1, 'y':2}.
  2. Step 2: Combine two lists

    Using + concatenates lists: [1,2] + [3,4] = [1,2,3,4].
  3. Final Answer:

    {'x': 1, 'y': 2} and [1, 2, 3, 4] -> Option D
  4. Quick Check:

    Dict merge and list concat produce {'x': 1, 'y': 2} and [1, 2, 3, 4] outputs [OK]
Quick Trick: Use ** to merge dicts and + to join lists [OK]
Common Mistakes:
MISTAKES
  • Expecting error when merging dicts
  • Adding extra elements to lists
  • Returning original dict instead of merged

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes