Problem with Crystal Rush, array change when printing in different lines

Hi, I have a problem with the Crystal Rush game, in the game you have a “ore” value for every cell of the game field, the value is “?” or a number.
I made a grid (2D array) with a -1 value if the corresponding cell is “?” or the ore value.
When I print the array during the initialization all the numbers are correct, if I print the array after the loop all values are -1. Why did this happen?

P.S. I don’t know if the category is correct, if it’s not correct me

The problem is that you create your ore_table like this:

ore_table=[ [0 for i in range(width)]] * height

With this your problem shouldn’t arise:

ore_table=[[0 for i in range(width)] for j in range(height)]

I don’t know if you are familiar with that problem:

list1 = [1,2,3,4,5]
list2 = list1
list1[0] = 0

Output: [0, 2, 3, 4, 5]

The problem is, that list2 = list1 doesn’t copies all the values, but it just means, that list2 and list1 are linked. So if you change one value in one list, it’s also changed in the other list. You can avoid that problem by writing:

list2 = list1.copy()

And your problem is the same, but a bit more tricky. If you multiply a list, the same thing happens. You have now several copies of one list and if you change a value in one of them it’s changed also in all the others. If you use what I wrote, this problem doesn’t appear, because you create always a new array for a new line. The thing with coping lists in Python is a very common mistake and a bit tricky. I only described it very short but you can find a lot of good explanations with more details on the internet.

1 Like

Thank you for the detailed answer, this solved the problem!
I didn’t know of this thing in python, thank you again! :smiley: