can't modify copy of array without changing original array

Question:

I tried modifying the array "newTab" but without use tab.copy() but it always modifies the original array.

tab = [[1]*2]*3
newTab = [None] * len(tab)
for i in range(0, len(tab)):
    newTab[i] = tab[i]

newTab[0][0] = 2
print(tab)
[[2, 1], [2, 1], [2, 1]]
print(newTab)
[[2, 1], [2, 1], [2, 1]]

I also tried using something like this :
a = b[:]
but it doesn’t work.
Somehow the original array is always a reference to the new one.
I just started learning python and we can only use the basics for our homework. So i’m not allowed to use things like deepcopy()
Any help would be appreciated!

Asked By: Patrick Kelvin

||

Answers:

You could use the copy library.

import copy

tab = [[1] * 2] * 3
newTab = [None] * len(tab)
for i in range(len(tab)):
    newTab[i] = copy.deepcopy(tab[i])
    newTab[i][0] = 2

print(tab)
print(newTab)
Answered By: Shawn Bragdon
tab = [[1]*2]*3
tab2 = []
for t in tab:
    tab2.append(t.copy())
#check that it worked - none of the values from tab2 should be the same as tab:
for t in tab:
    print(id(t))
for t in tab2:
    print(id(t))

as for why this happens: technically, things like lists and dictionaries are pointers in python. meaning, you aren’t handling the list itself, you are holding an address to where your info is stored. Thus, when you just assign a new variable to your list (that’s inside another list), you’re saying "I want to point to this address" , not "I want to put that same thing in another memory address"

Answered By: KEcoding
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.