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!

2
  • 1
    tab and newTab are both pointing to the same objects. Besides copying the list, what are you actually trying to accomplish? Commented Nov 12, 2022 at 0:12
  • Does this answer your question? List of lists changes reflected across sublists unexpectedly Commented Nov 12, 2022 at 0:13

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

what exactly does import copy do? I've seen people use it multiple times but i don't know what it does
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.
Okay thanks. Unfortunately, i can't use that either...
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"

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.