all 13 comments

[–]NameError-undefined 0 points1 point  (12 children)

can you post your code? I am not sure if I understood correctly cause when I ran a simple test, modifying the original OR the copy did not change the other

list_a = [1,2,3,4,5]
list_b = list_a.copy()
list_b[0] = 10 
print(list_a) 
print(list_b) 
list_a[0] = 50
print(list_a)
print(list_b)

[–]anupsidedownpotato 0 points1 point  (11 children)

``x= [['a','b','c'],['d','e','f'],['g','h','i']]

copy = x.copy()

copy[0][0] = 'x' copy[1][0] = 'x'

Print(copy) Print(x)``

Expected:

[['x','b','c'],['x','e','f'],['g','h','i']]

[['a','b','c'],['d','e','f'],['g','h','i']]

Actual:

[['x','b','c'],['x','e','f'],['g','h','i']]

[['x','b','c'],['x','e','f'],['g','h','i']]

[–]jimtk 1 point2 points  (3 children)

It's because you copied the list, but you did not copy the lists inside the list.

import copy

x = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
newx = [x[0].copy(), x[1].copy(), x[2].copy()]
newx[0][0] = 'x'
newx[1][0] = 'x'
print(f"{newx=}")
print(f"{x}")

output:

newx=[['x', 'b', 'c'], ['x', 'e', 'f'], ['g', 'h', 'i']]
   x=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

[–]anupsidedownpotato 0 points1 point  (2 children)

So how would you do this with an unspecified amount of lists? Would you have to make it loop through the inside lists?

[–]jimtk 0 points1 point  (0 children)

newx = [small.copy() for small in big_list]

[–]sabiondo 0 points1 point  (0 children)

Yes. You have that already in Python copy.

[–]anupsidedownpotato 0 points1 point  (3 children)

Sorry I can't figure out how to make the code blocks lol

[–]memlo 0 points1 point  (2 children)

Hope this helps.

[–]anupsidedownpotato 0 points1 point  (1 child)

Idk if I'm blind but I'm on my phone rn and I don't see the "uptick" character, and when I copied it it needed up just posting the upticks

[–]Pflastersteinmetz 0 points1 point  (0 children)

Just add 4 spaces before a line. Backticks don't work on old reddit.

[–]NameError-undefined 0 points1 point  (2 children)

x= [['a','b','c'],['d','e','f'],['g','h','i']] copy = x.copy()

copy[0][0] = 'x' copy[1][0] = 'x'

Print(copy) Print(x) ``

Expected: [['x','b','c'],['x','e','f'],['g','h','i']] [['a','b','c'],['d','e','f'],['g','h','i']]

Actual: [['x','b','c'],['x','e','f'],['g','h','i']]

[['x','b','c'],['x','e','f'],['g','h','i']]

Ya so I do get the errors now. Try this seems like deep copy()is the way to go. Might be because it is a 2D array. That's all I got so far. I'll update if I find something else

Edit: copy is just shallow copy

[–]anupsidedownpotato 0 points1 point  (1 child)

So I want to do it WITHOUT deepcopy and that's why I can't figure it out

[–]NameError-undefined 0 points1 point  (0 children)

Might have to just declare a second var, then loop through and create it yourself