Array of arrays is not displayed correctly

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By oohdee

I have a function that creates an array of random integers and then adds the array to a different one. For some reason, the other_array is displayed as empty. Am I doing something wrong?

func spin(col :int, row:int):
	var new_spin := []
	for i in range(col):
		for l in range(row):
			new_spin.append(random_value())
		other_array.append(new_spin)
		print(new_spin)
		new_spin.clear()

Output:
[0, 5, 4, 0, 1]
[4, 0, 2, 2, 4]
[5, 3, 2, 2, 2]
[2, 3, 3, 0, 0]
[2, 3, 4, 1, 2]
[, , , , ]
— Debugging process stopped —

:bust_in_silhouette: Reply From: oohdee

Ok, can I answer my own question? Because I found a solution.

So apparently I can’t insert arrays into an array “the Python way”. Instead, this way works fine:

func spin(col :int, row:int):
	for i in range(col):
		other_array.append([])
		for l in range(row):
			other_array[i].append(random_value())

To be clear, the original problem is the fact that you really only had a single array that you used to build a row of data, append that data to another array, and then clear that single array in preparation for the next row.

Since arrays are passed by reference, all of the above really interacted with the same, single array - including the call to clear(). So, your collection array just contained any number of references to a single array, which is emptied in your loop. So, ending up with a bunch of empty arrays is expected here.

The key here is to either 1) ensure that each row is a unique array (and, therefore, doesn’t need to be cleared within the loop) or 2) use Array.duplicate() to append a copy of the array data to your collection array.

Your new code is effectively a variation of the first suggestion above.

jgodfrey | 2023-03-06 15:09