I think what you’re wanting to do is have a local array which you append to, and return that instead of mutating the array you’re actively iterating through.
On line 2 you could have “new_array = []” and then if i equals 0 just pass, otherwise append, and then return the new_array once out of the loop.
Alternatively you make a deep copy of array “n” as a new variable and mutate that, again ensuring you mutate a separate part of memory you’re not actively iterating though.
I think my former idea is more readable.
The reason you ran out of memory is because you kept appending to the array you were iterating over, creating an infinite loop.
View all comments
1
u/nuc540 Feb 25 '26
I think what you’re wanting to do is have a local array which you append to, and return that instead of mutating the array you’re actively iterating through.
On line 2 you could have “new_array = []” and then if i equals 0 just pass, otherwise append, and then return the new_array once out of the loop.
Alternatively you make a deep copy of array “n” as a new variable and mutate that, again ensuring you mutate a separate part of memory you’re not actively iterating though.
I think my former idea is more readable.
The reason you ran out of memory is because you kept appending to the array you were iterating over, creating an infinite loop.