Reading history

Python Mutable vs Immutable, Shallow and Deep Copy

6 min read 2 views

Understand Python names and objects: mutable vs immutable types, function arguments, the mutable default argument trap, shallow vs deep copy, and == vs is.

Why did changing one list also change another? Why does a function’s default list keep growing between calls? These puzzles have one cause: in Python, a variable is a name attached to an object, not a box that holds a value. Some objects are mutable and can change in place (lists, dictionaries, sets), and some are immutable and never change (numbers, strings, tuples). This lesson explains how names, objects and copies really work, and how to avoid the classic bugs.

In this lesson you will learn

  • How assignment attaches a second name to the same object
  • Mutable vs immutable types
  • What happens to arguments passed to a function
  • The mutable default argument trap
  • Shallow vs deep copies, and == vs is

You should know lists, dictionaries and functions.

Names, Objects and Functions

# Names are labels attached to objects
a = [1, 2, 3]
b = a                       # b is another label for the SAME list
b.append(4)
print(a, a is b, id(a) == id(b))

# Immutable objects cannot change, so "changing" makes a new object
s = "dhaka"
t = s
t = t.upper()
print(s, t, s is t)

n = 10
m = n
m += 1
print(n, m)

# Functions receive the object itself, not a copy
def add_bonus(marks, bonus):
    marks.append(bonus)      # changes the caller's list
    bonus += 5               # only rebinds the local name
    return bonus

scores = [80, 75]
extra = 3
print(add_bonus(scores, extra), scores, extra)

# The mutable default argument trap
def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("pen"), add_item("ruler"))   # same list reused!

def add_item_safe(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print(add_item_safe("pen"), add_item_safe("ruler"))

Output

[1, 2, 3, 4] True True
dhaka DHAKA False
10 11
8 [80, 75, 3] 3
['pen', 'ruler'] ['pen', 'ruler']
['pen'] ['ruler']
  • b = a does not copy the list. It attaches a second name to the same object, so appending through b also changes what a sees. a is b is true.
  • Strings and integers are immutable. t.upper() and m += 1 create new objects and move the name to them; the original values stay untouched.
  • A function receives the caller’s object itself. marks.append(bonus) changed the caller’s scores list, but bonus += 5 only rebound the local name, so extra stayed 3.
  • A default value is created once, when the function is defined. basket=[] is the same list on every call, so items pile up: both calls printed the same list, since it now held both items.
  • The safe pattern is basket=None and creating a fresh list inside the function.

Shallow and Deep Copies

import copy

classes = {"CSE": ["Nusrat", "Tania"], "EEE": ["Arif"]}

shallow = copy.copy(classes)          # same as dict(classes) or classes.copy()
deep = copy.deepcopy(classes)

shallow["BBA"] = ["Imran"]            # new key: only in the shallow copy
shallow["CSE"].append("Mitu")         # inner list is SHARED with the original
deep["EEE"].append("Rafi")            # deep copy has its own inner lists

print("original:", classes)
print("shallow: ", shallow)
print("deep:    ", deep)
print(classes["CSE"] is shallow["CSE"], classes["EEE"] is deep["EEE"])

# Copying a 2D grid: the [[0]*3]*3 trap
bad = [[0] * 3] * 3
bad[0][0] = 9
print(bad)
good = [[0] * 3 for _ in range(3)]
good[0][0] = 9
print(good)

# == compares values, is compares identity
x = [1, 2]
y = [1, 2]
print(x == y, x is y, x is not None)

# Tuples are immutable, but can hold mutable items
t = ([1, 2], "fixed")
t[0].append(3)
print(t)
try:
    t[1] = "changed"
except TypeError as e:
    print("TypeError:", e)

Output

original: {'CSE': ['Nusrat', 'Tania', 'Mitu'], 'EEE': ['Arif']}
shallow:  {'CSE': ['Nusrat', 'Tania', 'Mitu'], 'EEE': ['Arif'], 'BBA': ['Imran']}
deep:     {'CSE': ['Nusrat', 'Tania'], 'EEE': ['Arif', 'Rafi']}
True False
[[9, 0, 0], [9, 0, 0], [9, 0, 0]]
[[9, 0, 0], [0, 0, 0], [0, 0, 0]]
True False True
([1, 2, 3], 'fixed')
TypeError: 'tuple' object does not support item assignment
  • A shallow copy (copy.copy, dict.copy(), list(x) or x[:]) makes a new outer container, but the items inside are the same objects. Adding a key to the copy did not affect the original, but appending to the shared inner list did.
  • A deep copy (copy.deepcopy) copies every level, so changes to it never reach the original.
  • [[0] * 3] * 3 creates three references to one inner list, so setting one cell changed all three rows. A list comprehension builds three separate lists.
  • == asks “do they have equal values?”; is asks “are they the same object?”. Use is only for None, True and False.
  • A tuple is immutable, so its slots cannot be reassigned, but a list stored inside it can still change.

Mutable and Immutable Types

Immutable (cannot change)Mutable (can change in place)
int, float, bool, complexlist
strdict
tupleset
frozenset, bytesbytearray, most custom objects

Only immutable (hashable) values can be dictionary keys or set members, which is why a tuple works as a key but a list does not.

Common Mistakes

  1. Thinking b = a makes a copy of a list or dictionary.
  2. Using a mutable default argument such as def f(x=[]) or def f(d={}).
  3. Making a shallow copy of nested data and then changing an inner list.
  4. Comparing values with is, such as if name is "Dhaka". It may work by accident for short strings and fail elsewhere.

Practice Exercises

Exercise 1. What does this print? x = [1, 2]; y = x + [3]; x.append(9); print(x, y)

Show answer

[1, 2, 9] [1, 2, 3]. The + operator builds a brand-new list, so y is not affected by the later append to x.

Exercise 2. Write add_tag(tags, new) that returns a new list with the tag added, without changing the caller’s list.

Show answer
def add_tag(tags, new):
    return tags + [new]          # or: copy = list(tags); copy.append(new); return copy

original = ["python"]
updated = add_tag(original, "sql")
print(original, updated)        # ['python'] ['python', 'sql']

Frequently Asked Questions

Is Python pass-by-value or pass-by-reference?

Neither exactly. Python passes a reference to the object, sometimes called “pass by object reference”. A function can change a mutable object it receives, but assigning a new value to the parameter only changes the local name.

Is deepcopy slow?

It can be for large nested structures, because it copies every level and keeps track of objects it has already copied. Use it when you really need fully independent data; otherwise a shallow copy is cheaper.

Summary

  • Variables are names attached to objects; assignment never copies.
  • Mutable objects change in place; immutable ones are replaced.
  • Use None as a default instead of a mutable value.
  • Shallow copies share inner objects; deepcopy copies everything.

Next: Python Abstract Classes (abc).

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *