Free memory in Python

断了今生、忘了曾经 提交于 2019-12-01 11:40:54

You cannot really free memory manually in Python.

Using del decreases the reference count of an object. Once that reference count reaches zero, the object will be freed when the garbage collector is run.

So the best you can do is to run gc.collect() manually after del-ing a bunch of objects.


In these cases the best advice is usually to try and change your algorithms. For example use a generator instead of a list as Thijs suggests in the comments.

The other strategy is to throw hardware at the problem (buy more RAM). But this generally has financial and technical limits. :-)

You can delete an item in list via four popular methods (including collections.deque) :

list remove() method :

remove removes the first matching value, not a specific index

remember This method does not return any value but removes the given object from the list.

example :

list_1 = [987, 'abc', 'total', 'cpython', 'abc'];
list_1.remove('abc')
print(list_1)
list_1.remove('total')
print(list_1)

output:

[987, 'total', 'cpython', 'abc']
[987, 'cpython', 'abc']

Second method is list del() method

You have to specify the index_no here

list_1 = [987, 'abc', 'total', 'cpython', 'abc'];
del list_1[1]
print(list_1)
del list_1[-1:]
print(list_1)

output:

[987, 'total', 'cpython', 'abc']
[987, 'total', 'cpython']

Third one is list pop() method :

pop() removes and returns the last item in the list.

list_1 = [987, 'abc', 'total', 'cpython', 'abc'];
list_1.pop()
print(list_1)
list_1.pop()
print(list_1)
list_1.pop()
print(list_1)

output:

[987, 'abc', 'total', 'cpython']
[987, 'abc', 'total']
[987, 'abc']

Forth method is collections.deque

There are some more external module methods like :

You can pop values from both sides of the deque:

from collections import deque

d = deque()

d.append('1')
d.append('2')
d.append('3')
print(d)

d.popleft()
print(d)
d.append('1')
print(d)

d.pop()
print(d)

output:

deque(['1', '2', '3'])
deque(['2', '3'])
deque(['2', '3', '1'])
deque(['2', '3'])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!