ck1987pd
ck1987pd

Reputation: 269

What happens have you create an object with a name already used before in python?

I am creating objects in a loop and I have no use of them after the loop counter moves forward. The pseudo code should appear like this:

for i in range(N):
    A=object_creator(a,b,c[i])
    some_array[i]=A.some_function()

Should I include a del A command in the loop for memory preservation or since its reference is reused, is the memory deallocated?

Apologies if it is a duplicate question.

Upvotes: 0

Views: 67

Answers (1)

Josh Hayes
Josh Hayes

Reputation: 38

In short, no, you don't need to include del A. For a full explanation, I recommend you have a look here: https://www.geeksforgeeks.org/garbage-collection-python/

From the first paragraph:

Python’s memory allocation and deallocation method is automatic. The user does not have to preallocate or deallocate memory similar to using dynamic memory allocation in languages such as C or C++.

This is Python's internal garbage collection - it will clean up the memory of unreferenced object automatically. As a general rule, try and avoid using del whenever possible.

Upvotes: 1

Related Questions