S
S
Sazoks2020-09-19 10:18:56
Python
Sazoks, 2020-09-19 10:18:56

How does memory cleanup work in Python?

Good afternoon! We started studying Python in the 1st year of the university.
After 3 years of C++, it is fundamentally important for me to know how everything works under the hood.
The teachers, unfortunately, are young graduate students and know little themselves.

Please tell me if I remove an element from the list in any of the following ways: del x[1], x.pop[1], x.remove[1]. Will the data be stored in memory?

x = [1, 2, 3, 4, 5]
a = x[4]
x.remove(5)
print(a)

print(a) will print 5 to the console, even though I seem to have deleted the data. The same thing happens with del and c pop. I know that in Python all variables are object references. And all these methods just remove links, but what to do with unnecessary data? Do they really remain hanging in memory until the end of the program?

I will be very grateful for your answers!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sswwssww, 2020-09-19
@Sazoks

If there are no references to the object in memory (object reference count = 0 (actually not exactly 0, but this is already connected with the internal mechanisms of the interpreter, this should not worry us)) - the object is deleted by the garbage collector. You don't have to worry about deleting objects.
Those. in your example, references to the object still remain (a = x[4]) , so the object is not automatically deleted.

K
kirillinyakin, 2020-09-19
@kirillinyakin

Python implements automatic garbage collector

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question