1. Home
  2. Interview Questions
  3. Python
  4. What is the difference between assignment, shallow copy and …

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: Assignment copies nothing and only binds a second name to the same object. A shallow copy creates a new outer container that still holds references to the same inner objects, while a deep copy (copy.deepcopy) recursively copies the inner mutable objects as well, so the result shares no mutable state with the original.

Detailed explanation

Python variables are names that refer to objects. Most copying confusion goes away once you ask one question: is this a new object, or another reference to an existing one?

  • Assignment (b = a) creates no new object. Both names point to the same object, so a is b is True. Any change made through one name is visible through the other.
  • Shallow copy creates a new top-level container and fills it with references to the same elements. Ways to make one include copy.copy(x), lst.copy(), lst[:], list(lst), dict.copy(), dict(d) and set(s). Adding to or removing from the copy does not affect the original. Mutating a nested object, such as an inner list, does affect it, because that inner object is shared.
  • Deep copy (copy.deepcopy(x)) walks the whole object graph and creates new copies of the mutable objects it finds. Changes to nested data in the copy never reach the original.

A few details separate experienced candidates from freshers:

  • Immutable objects are usually not duplicated. Integers, strings and tuples that contain only immutables are returned as the same object by deepcopy. Copying them would be pointless because they cannot change. A tuple that contains a list is copied, because the list inside it must be new.
  • deepcopy uses a memo dictionary. It records every object it has already copied. This lets it handle circular references, such as a list that contains itself, without infinite recursion. It also preserves shared structure: if two slots refer to the same inner list, the deep copy will also have two slots referring to one new list.
  • Custom classes can control copying by defining __copy__(self) and __deepcopy__(self, memo). This is useful when an object holds things that should not be duplicated, such as a database connection or a cache.
  • Some objects cannot be deep-copied. Objects such as locks, open files and sockets typically raise a TypeError, because deepcopy falls back on the pickle protocol for objects it does not know how to copy.
  • Cost: deepcopy is much slower than a shallow copy and uses more memory on large structures. Use it when you genuinely need independent nested data.

Example

import copy

original = [[1, 2], [3, 4]]

alias   = original                 # assignment
shallow = copy.copy(original)      # same as original[:]
deep    = copy.deepcopy(original)

original[0].append(99)   # mutate a nested list
original.append([5])     # change the outer list

print(alias)    # [[1, 2, 99], [3, 4], [5]]
print(shallow)  # [[1, 2, 99], [3, 4]]
print(deep)     # [[1, 2], [3, 4]]

print(alias is original)          # True
print(shallow is original)        # False
print(shallow[0] is original[0])  # True  - inner list shared
print(deep[0] is original[0])     # False - inner list copied

# Circular reference handled by deepcopy's memo
a = [1]
a.append(a)
b = copy.deepcopy(a)
print(b[1] is b)   # True - the cycle is reproduced, no recursion error

The shallow copy did not get the new [5] because its outer list is separate. It did see 99 because shallow[0] and original[0] are the same inner list.

Common mistakes

  • Assuming b = a makes a copy, then being surprised when changes made through b show up in a.
  • Using lst[:] or dict.copy() on nested data, such as a list of lists or a dict of lists, and expecting full independence. A common example is copying a config dict and then editing a nested list inside it.
  • Creating a grid with [[0] * 3] * 3. All three rows are the same list object, so setting grid[0][0] = 1 changes every row. Use [[0] * 3 for _ in range(3)] instead.
  • Reaching for deepcopy everywhere out of caution. It slows hot code paths and can fail on objects that hold resources such as locks, files or connections.

Follow-up questions

  • How does deepcopy avoid infinite recursion on self-referencing objects, and what is the memo argument?
  • How would you implement __deepcopy__ for a class that holds a database connection that must not be duplicated?
  • Why does copy.copy on a tuple return the same object, and when does deepcopy return a new tuple?

Interview tip: Draw or describe the references: one outer box pointing to shared inner boxes for a shallow copy, and fully separate boxes for a deep copy. Then confirm your explanation with is checks on the nested elements.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More medium Python questions

All medium questions →

Related Questions

‹
Q10 of 10 · Python
All ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA