4

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:

1
list_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.

2
m = 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?

Travis
  • 1,152
  • 9
  • 25

1 Answers1

0

First of all with list_ori = [[0 for i in range(3)] for j in range(3)], there is no need to deepcopy, just do:

list_ori = [[0 for i in range(3)] for j in range(3)]
list_copy[0][0] = 1 
print(list_copy)

Output:

[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    Thank you! It is the same with my solution 1. But I wanna know why `copy.deepcopy` failed in my example code – Travis Feb 25 '19 at 04:14
  • @Travis Happy to help, regarding `deepcopy`, it fails because you're copying the based list, not copying directly to the sublists too. – U13-Forward Feb 25 '19 at 04:15
  • 1
    @Travis see https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – U13-Forward Feb 25 '19 at 04:18
  • 2
    I don't think this answer answers the question even a little. OP is asking why `deepcopy` doesn't give him three different objects of `[0]*3`. According to the source code: https://github.com/python/cpython/blob/16323cb2c3d315e02637cebebdc5ff46be32ecdf/Lib/copy.py#L138 . It seems `deepcopy` caches the same instances(have the same `id`). – Sraw Feb 25 '19 at 04:23