Bird
Raised Fist0

Consider the following Python code snippet:

easy📖 Theory Q3 of Q15
OOP & Design Patterns - Prototype Pattern - Deep Copy vs Shallow Copy
Consider the following Python code snippet:
import copy

class Student:
    def __init__(self, name, grades):
        self.name = name
        self.grades = grades

original = Student('Alice', [90, 85])
copied = copy.deepcopy(original)
copied.grades.append(95)
print(original.grades)

What will be the output of this code?
A[95]
B[90, 85, 95]
CError due to modifying copied object
D[90, 85]
Step-by-Step Solution
Solution:
  1. Step 1: Understand deepcopy behavior

    Deepcopy creates a new object and recursively copies nested mutable objects.
  2. Step 2: Analyze the code

    The copied object's grades list is modified by appending 95, but the original's grades list remains unchanged.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Original list unchanged after deepcopy modification [OK]
Quick Trick: Deepcopy isolates nested mutable objects from original [OK]
Common Mistakes:
MISTAKES
  • Assuming shallow copy was used and original list changes
  • Confusing reference copy with deepcopy
  • Expecting an error when modifying copied object
Trap Explanation:
PITFALL
  • Option B looks plausible if one mistakes deepcopy for shallow copy.
Interviewer Note:
CONTEXT
  • Tests understanding of deepcopy effect on nested mutable fields.
Master "Prototype Pattern - Deep Copy vs Shallow Copy" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes