Skip to content

script_17.py - List Copying

Code

See script_17.py for full code.

Explanation

Line 8: import copy - copy module for deep copying

Line 12: original = [1, 2, 3, 4, 5] - Simple list of integers - Integers are immutable (can't be modified)

Line 15: copy1 = original[:] - Slice notation creates shallow copy - New list object created - Elements are references (not copies) - For immutable elements (int, str), behaves like deep copy

Line 16: copy1[0] = 99 - Modifies copy, not original - Works because lists are mutable

Line 20: copy2 = list(original) - list() constructor creates copy - Equivalent to slice method

Line 25: copy3 = original.copy() - .copy() method (Python 3.3+) - Also creates shallow copy

Line 31: matrix = [[1, 2], [3, 4], [5, 6]] - Nested list (list of lists) - Inner lists are mutable objects

Line 35: shallow = matrix.copy() - Creates new outer list - Inner lists are same objects (references) - Shallow copy only copies one level

Line 36: shallow[0][0] = 999 - Modifies inner list - shallow[0] and matrix[0] are same object - Changes visible in both!

Line 44: deep = copy.deepcopy(matrix2) - .deepcopy() recursively copies all nested objects - Creates completely independent copy - Inner lists are new objects

Line 45: deep[0][0] = 999 - Modifies deep copy's inner list - Original unchanged (different objects)

Line 58: def add_task(self, task): - Method modifying list

Line 60: self.history.append(copy.deepcopy(self.tasks)) - Saves deep copy of current state - Necessary for undo functionality - Without deepcopy, history would reference same list

Line 65: self.tasks = self.history.pop() - Restores previous state - Replaces current list with saved copy

Line 79: list_a = [1, 2, 3] - Original list

Line 80: list_b = list_a - Assignment creates reference, NOT copy! - Both variables point to same list object

Line 81: list_b.append(4) - Modifies the list - Both list_a and list_b see the change - They're the same object