I know copy and deepcopy of a list.However, this question is a bit different, because my original list is generated by multiplying element.
First I generate original list by list_ori = [[0]*3]*3
.
What I want is revising [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
and then get [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
I tried with following code.
import copy
list_ori = [[0]*3]*3
list_copy = copy.deepcopy(list_ori)
list_copy[0][0] =1
print(list_copy)
Thus,I got [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
.
But actually,I want to get [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
I have 2 naive solutions, but I was wondering is there a more clear way to deal with list_ori = [[0]*3]*3
by deepcopying and then revising it?
Two naive solutions:
1list_ori = [[0 for i in range(3)] for j in range(3)]
list_copy = copy.deepcopy(list_ori)
list_copy[0][0] =1
print(list_copy)
I change the generating method of list.The list_ori is not with duplicated elements in a list.
2m = n = 3
test = [[0] * m] * n
print(test)
test_copy = [copy.copy(element) for element in test]
test_copy[0][0] = 1
print(test_copy)
This method iterates elements of a list. Will this method destroy the structure of list?