List of lists changes reflected across sublists unexpectedly
In Python, when you create a list of lists and modify one of the sublists, the change is reflected in all other sublists as well because they are all pointing to the same object in memory. This is known as a "shallow copy" of the list of lists.
Here is an example:
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Create a shallow copy of the list
copied_list = original_list.copy()
# Modify the first sublist of the copied list
copied_list[0][1] = 99
# Print the original list
print(original_list)
# Output: [[1, 99, 3], [4, 5, 6], [7, 8, 9]]
As you can see, the change made to the first sublist of the copied_list is reflected in the original_list as well.
To make a true copy of the list of lists, you should use the copy.deepcopy()
function from the copy
module.
import copy
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Create a deep copy of the list
copied_list = copy.deepcopy(original_list)
# Modify the first sublist of the copied list
copied_list[0][1] = 99
# Print the original list
print(original_list)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Now, changes made to the sublists of the copied_list do not affect the original_list