How to remove an item in list once used from a large list in python to save the memory?

3032 views python

If i have large list which runs in millions of items, i want to iterate through each of them. Once i use the item it will never be used again, so how do i delete the item from the list once used? What is the best approach? I know numpy is fast and efficient but want to know how it can be done using normal list.

mylst = [item1, item2,............millions of items]
for each_item in mylist:
    #use the item
    #delete the item to free that memory

answered question

The entire list will be garbage collected after you are done and you are not using the list after that, why do you need to remove items individually?

1 Answer


You cannot delete an object directly in Python - an object's memory is automatically reclaimed, by garbage collection, when it's no longer possible to reference the object. So long as an object is in a list, it may be referenced again later (via the list).

So you need to destroy the list too. For example, like so:

while mylst:
    each_item = mylst.pop()  # removes an object from the end of the list
    # use the item

posted this

Have an answer?


Please login first before posting an answer.