- Home
- Interview Questions
- Python
- 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
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, soa is bisTrue. 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)andset(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, becausedeepcopyfalls back on the pickle protocol for objects it does not know how to copy. - Cost:
deepcopyis 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 errorThe 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 = amakes a copy, then being surprised when changes made throughbshow up ina. - Using
lst[:]ordict.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 settinggrid[0][0] = 1changes every row. Use[[0] * 3 for _ in range(3)]instead. - Reaching for
deepcopyeverywhere 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
deepcopyavoid infinite recursion on self-referencing objects, and what is thememoargument? - How would you implement
__deepcopy__for a class that holds a database connection that must not be duplicated? - Why does
copy.copyon a tuple return the same object, and when doesdeepcopyreturn 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
Related Questions
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- Why does Pandas raise SettingWithCopyWarning and how do you fix chained assignment correctly? · Python · 1 ans
- What is broadcasting in NumPy and what rules decide whether two arrays can be combined? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- What is exception chaining in Python and when should you use raise from? · Python · 1 ans
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)