Unexpected behavior when deleting elements from a multi-dimensional array in Python
I've been struggling with this for a few days now and could really use some help. After trying multiple solutions online, I still can't figure this out... I've looked through the documentation and I'm still confused about I'm working with a nested list in Python that represents a grid of values. I need to remove certain elements based on their values, but I'm encountering unexpected behavior during the deletion process. For example, I have the following grid: ```python grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` I want to remove all instances of the value `5`. My approach has been to loop through the main list and then check each sub-list for the value to remove. Here's what I implemented: ```python for row in grid: if 5 in row: row.remove(5) ``` After executing this code, I expected the grid to change to: ``` [ [1, 2, 3], [4, 6], [7, 8, 9] ] ``` However, I noticed that if I run this code multiple times, it seems to remove the value from the first occurrence only. When I print the `grid` after multiple executions, I sometimes see unexpected results: ``` [ [1, 2, 3], [4, 6], [7, 8, 9] ] ``` This behavior is quite confusing. I've also tried using a list comprehension to create a new grid, like so: ```python grid = [[value for value in row if value != 5] for row in grid] ``` ``` But this gives me the right output without the instances of `5`, but I am concerned about performance when dealing with larger grids. I'm currently using Python 3.8. Could anyone explain why the first approach isn't working as I expected? Is there a more efficient way to handle this kind of operation with better performance in mind for larger datasets? Am I missing something obvious? For context: I'm using Python on Ubuntu 20.04. Any pointers in the right direction?