-2

Here a screenshot of output. Please explain why it works this way and provide me with a solution on how to make the copy of a list of lists

the result of work

matrix = [['I','A','O','O','I'],['I','A','O','O','I'],['I','A','O','O','I'],['I','A','O','O','I'],['I','A','O','O','I']]

matrix_1d = ['I','A','O','O','I']

matrix2 = matrix.copy()
matrix2_1d = matrix_1d.copy()
def printMat(m):
    for i in range(len(m)):
        print (m[i])

matrix[0][0] = 'lol'
matrix2[0][1] = 'kek'

matrix_1d[0] = 'lol'
matrix2_1d[1] = 'kek'

printMat(matrix)
print("_")
printMat(matrix2)
print("_")
print(matrix_1d)
print("_")
print(matrix2_1d)
  • 2
    Your output and code are both text, don't post links to screenshot of it. Copy paste them into the question – UnholySheep Feb 08 '19 at 23:53
  • 1
    `.copy` creates a shallow copy. The inner objects are not copied, a reference to them is put in a *new list*. You want a *deep copy*. – juanpa.arrivillaga Feb 08 '19 at 23:57
  • As per @juanpa.arrivillaga https://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm – run-out Feb 08 '19 at 23:58

1 Answers1

0

The documentation clearly states:

Return a shallow copy of the list.

What you want instead is a deep copy.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Thanks ! But why I have copies in 1d list if i should have references to initial list? – Borys Altynnyk Feb 09 '19 at 00:10
  • @BorysAltynnyk it works **exactly** the same. Your "1-d" list copy has references to the items in the original list, just as your "2-d" list copy does. You can check the `id`'s for yourself. And they aren't references to the *initial list*, they are references to the *objects contained by the original list*. – juanpa.arrivillaga Feb 09 '19 at 00:22
  • @juanpa.arrivillaga. But if objects of new list are references to objects of the initial list, why changing them in copy list don't affect them in the initial list? (Have a look on the picture attached, you will understand what I am talking about) – Borys Altynnyk Feb 09 '19 at 07:40
  • @BorysAltynnyk you never try to change them. You *change the list*. Where do you believe you try to change the objects in the "1-D" list? – juanpa.arrivillaga Feb 09 '19 at 18:48
  • @BorysAltynnyk When you do `matrix2_1d[1] = 'kek'`, you assign the reference at index `1` of the copied list to point to a different object. **This does not change the object referenced by the original list**. Nor does it change any reference in the original list. – Code-Apprentice Feb 09 '19 at 22:24