How do I clone a list so that it doesn’t change unexpectedly after assignment in Python?

To clone a list in Python so that changes to the cloned list do not affect the original, you need to create an independent copy of the list. The method depends on whether the list contains mutable nested objects (like other lists, dictionaries) or only immutable elements (like integers, strings).

1. Shallow Copy (Top-Level Copy)

Use this when the list contains immutable elements or you don’t need to copy nested mutable objects.
Methods:

Option 1: Slice Operator

original = [1, 2, 3]
cloned = original[:]  # Creates a new list

Option 2: list() Constructor

cloned = list(original)

Option 3: copy() Method

cloned = original.copy()

Example:

original = [1, 2, 3]
cloned = original.copy()
cloned.append(4)

print(original)  # Output: [1, 2, 3]
print(cloned)    # Output: [1, 2, 3, 4]

2. Deep Copy (For Nested Mutable Objects)

Use this when the list contains nested mutable objects (e.g., lists of lists, dictionaries).
Method: Use copy.deepcopy() from the copy module.

import copy

original = [[1, 2], [3, 4]]
cloned = copy.deepcopy(original)
cloned[0].append(5)

print(original)  # Output: [[1, 2], [3, 4]] (unchanged)
print(cloned)    # Output: [[1, 2, 5], [3, 4]]

Why Deep Copy?
Shallow copies retain references to nested mutable objects:

original = [[1, 2], [3, 4]]
cloned = original.copy()  # Shallow copy
cloned[0].append(5)

print(original)  # Output: [[1, 2, 5], [3, 4]] (modified!)

Common Mistakes

Assignment (=) Does NOT Create a Copy

cloned = original  # Creates a reference, NOT a copy!
cloned.append(10)
print(original)    # Output: [1, 2, 3, 10] (original is modified)

Summary

ScenarioMethodCode Example
List with immutable elementsShallow copycloned = original.copy()
List with nested lists/dictsDeep copycloned = copy.deepcopy(original)
Quick top-level cloneSlice or list()cloned = original[:]

Key Takeaways:

  • Use shallow copy for flat lists (no nested mutable objects).
  • Use deep copy for nested or complex structures.
  • Avoid assignment (=) for cloning; it creates a reference, not a copy.

Leave a Reply

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