0

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!

  • 1
    `tab` and `newTab` are both pointing to the same objects. Besides copying the list, what are you actually trying to accomplish? – Paul H Nov 12 '22 at 00:12
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Swifty Nov 12 '22 at 00:13

2 Answers2

1

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)
kryozor
  • 315
  • 1
  • 7
  • what exactly does import copy do? I've seen people use it multiple times but i don't know what it does – Patrick Kelvin Nov 12 '22 at 00:34
  • Importing is like using modules in Lua with `require("module")`, or using a namespace in java like `import java.io.InputStream` for example. They just call for third party dependencies that the project needs to use. – kryozor Nov 12 '22 at 00:39
  • Okay thanks. Unfortunately, i can't use that either... – Patrick Kelvin Nov 12 '22 at 00:47
0
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"

KEcoding
  • 55
  • 3
  • I'm glad I could help - I had to learn C to finally understand this so I'm glad I could spare you the confusion. – KEcoding Nov 12 '22 at 01:17