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)
I am obliged to copy the elements of the old list as I then want to modify them independently. Is it correct?
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?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?