If I don't delete the Python list, will it remain in memory?

Asked 2 years ago, Updated 2 years ago, 22 views

 order_list= ["toothpaste", "soap", "toilet paper"]

    for i in order_list:
        save_list = []
        save_list.append(i)

In this way, we create and use save_list while touring the for door.

Isn't save_list generated and deleted from memory every time a for statement is executed?

It doesn't matter if it's small like the example above, but if there's a lot of data, a memory error pops up.

I thought save_list would be automatically deleted after the for statement is completed, so the memory would be returned and generated again.

It's not that, but I wonder if it's still in memory.

And if it's left in memory,

del save_list

Should I use the?

python

2022-09-22 18:27

1 Answers

If an object has a reference count of 0, it is subject to garbage collection, and the object disappears upon garbage collection.

In the code in the example, a new list object is created every time you traverse the for iteration statement and the previous list object loses its reference, so no matter how many times you generate the save_list, the previously created save_list is the target of the garbage collection, so it does not cause a memory error.

Presumably, regardless of the for statement below, the size of the order_list is too large to cause a memory error.


2022-09-22 18:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.