Delete an item from a 2D array

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


I have a simple question to a difficult problem: How do i delete an item from a 2D array?

		if selectedHearts.size() > 0:
		for x in range(8):
			for y in range(10):
				if selectedHearts.has(hearts[x][y].get_node("Sprite")):

I need to remove hearts[y] in the loop here. how do i do it?

Not sure what you want to achieve: Removing any element (e.g. with hearts.remove(y)) would break your loop, since now there would only be 9 y elements left for the given x, not 10. Moreover, its not clear which elements should fill the gap: Should y be reduced (like in my line above), or x? Do you have an example project?

Thomas Karcher | 2019-05-26 21:11
Here is all the code.

Everytime i queue_free() a node in hearts 2D array i get an error saying: “Attempt to call function ‘get_node’ in base ‘previously freed instance’ on a null instance.” in my find_neighbour() function.

what im trying to do is to that element from the 2D array and later refill it.

Joakim Wennergren | 2019-05-26 21:20

:bust_in_silhouette: Reply From: eons

Looks like your array is keeping refereces to previously removed nodes, remember to remove from the array too if you are storing it on a variable.

Also, when removing things on arrays, you must do it on a reverse order, it can be achieved with:

for i in range(array_size, 0, -1)

And in some cases, you may need to do extra checks with is_instance_valid(your_node)

:bust_in_silhouette: Reply From: Thomas Karcher

Thanks for the code! So you actually don’t want to change the array dimensions (it should remain an 8x10 array all the time), but you only want to have empty elements in there! That’s no problem, as long as you don’t ask the script to search for a Sprite within an empty element (which leads to the error shown above). So all you have to do is replace

if selectedHearts.has(hearts[x][y].get_node("Sprite")):


# Is there a node in this element?
if is_instance_valid (hearts[x][y]):
   # If yes: Check the Sprite within the node
   if selectedHearts.has (hearts[x][y].get_node ("Sprite")):