1

Below I create a list of Any instances, then I modify this list and finally I randomly chose some elements of this list in order to create a new list.

from random import choice
import copy

class Any():
    def __init__(self,x):
       self.x=x

    def modify (self):
        self.x += choice([0,1])
        return self

def create_new_list (old_list):
    new_list = [copy.deepcopy(old_list[choice(range(len(old_list)))]) for i in range(len(old_list))]
    return new_list


a = [Any(0),Any(19),Any(3),Any(10)] # Create the original list
for iteration in xrange(20):
    [i.modify() for i in a]
    a = create_new_list(a)
  1. I am obliged to copy the elements of the old list as I then want to modify them independently. Is it correct?

  2. Because of this system, I am creating, at every loop new instances of Any that will be kept in memory yielding to an issue of memory leak. Is it correct?

  3. How can I avoid this?

    3a) What if I add

    del old_list

    at the end of the function create_new_list?

    3b) Or should I add

    [del(i) for i in old_list]

    del old_list

    at the end of the create_new_list?

    3c) Is there another, more efficient solution?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Remi.b
  • 17,389
  • 28
  • 87
  • 168
  • A memory leak is when allocated memory isn't released. Python has garbage collection, so no memory leak is possible. – StoryTeller - Unslander Monica Feb 17 '14 at 17:14
  • The first instance of list `a` is eligible for release or garbage collection as soon as you no longer refer to it, ie, when you assign the list returned from `create_new_list` to `a`. There is no leak. – Useless Feb 17 '14 at 17:16

1 Answers1

1

In your case, no, you don't need to copy anything.

Furthermore, you don't need to explicitly deallocate anything. Things will be garbage-collected when they are no longer referenced.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Hum, I don't totally get the point. All the Any's instances that are not present in the new list. What happen to them? They take memory, don't they? They will garbage-collected. Does it mean they will be erased from the memory? How long does an instance need to not be referenced before it enters in the garbage-collection? – Remi.b Feb 17 '14 at 17:54
  • Python garbage collection deletes objects from memory once nothing else refers to them any more (i.e., the usual method of garbage collection). The details of when Python does garbage collection are somewhat involved, but well-described. See here: http://stackoverflow.com/questions/4484167/details-how-python-garbage-collection-works In general, worrying too much about garbage collection is usually a mistake in a language like Python. Profile your code instead and see where the actual issues occur. – Namey Feb 17 '14 at 21:05