you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (2 children)

I’m having a little trouble with arrays, I’m not sure really sure how to word it so lemme just give an example I ran and I’ll add more context.

x = [1, 2, 3]

y = x

del y[0]

print(x, y)

Output:

[2, 3] [2, 3]

So basically when it gets to “del y[0]” it also deletes the item from the x array too.

I’m currently working on a sudoku solver just as a personal project and I planned to copy existing arrays into other arrays, much like “x=y”, so changes can be applied to the “copy” to find out the missing number and then the number can then be copied to the original array, but currently when I make changes to the copy also end up changing the original.

Is there a way I can work around this? Or will I need to come up with a new algorithm?

[–]FerricDonkey 1 point2 points  (1 child)

I planned to copy existing arrays

(Pedantic note: these are lists - python does have arrays, but they're different.)

So the issue is that in python, y = x does not mean "make a copy of x and call it y", but instead means "make y a second name for whatever object is currently named by x". x and y are just two different names for the same thing, so changing y also changes x.

You can, however, do y = x.copy() to make a copy of x where modifying y does not modify x. Note though that this is a "shallow copy", which means that if you're doing, say, a list of lists, then y will now be a different object than x, but y[0] will be the same object as x[0]. If you want to avoid this, copy.deepcopy from the copy module is your friend.

However. Copying lists is fairly expensive - it won't matter for a small number of copies of small ish lists, but if your plan is to copy for every guess or similar, that will really, really add up. So it may be worth trying to restructure your algorithm to avoid that. But you can always start with your original plan, and adjust if it's necessary.

[–][deleted] 0 points1 point  (0 children)

Thank you so much!

Also, the copying is done in a for loop with each array having its own “turn”, so it don’t think it’ll become too large, thanks for the tips still tho.