🐍

Mutability and References

Programare Python Advanced 5 min read

Mutability and References

Mutable vs Immutable

Mutable Immutable
list, dict, set int, float, str, tuple

References

Variables are references to objects:

a = [1, 2, 3]
b = a       # Same object!
b.append(4)
print(a)    # [1, 2, 3, 4]

Copying

b = a[:]              # Shallow copy
b = copy.deepcopy(a)  # Deep copy

Mutable Default Argument Trap

# WRONG
def add(elem, lst=[]):
    lst.append(elem)
    return lst

# CORRECT
def add(elem, lst=None):
    if lst is None:
        lst = []
    lst.append(elem)
    return lst

Key Points

  • b = a creates reference, not copy
  • Shallow copy shares nested objects
  • NEVER use [] or {} as default!

📚 Related Articles