YourTeddy
YourTeddy

Reputation: 433

Does python delete a list while there is a copy of it

lista = [1, 2, 3, 4, 5]
listb = lista[:]
lista = 'somethingelse'
listb.pop()

So now, the list [1, 2, 3, 4, 5] still exist, or it is removed from the internal memory, or it is changed into [1, 2, 3, 4] with listb?

Upvotes: 0

Views: 161

Answers (2)

Let's see your code line by line.

lista = [1, 2, 3, 4, 5]

This would point the name lista to the list having values [1, 2, 3, 4, 5] (let's call it list#1).

listb = lista[:]

This would make a copy of the list above, and point the name listb to that copy (let's call it list#2); now essentially there are 2 lists with equal contents (list#1 and list#2)

lista = 'somethingelse'

This would cause the name lista to point to the string 'somethingelse'; the reference count of list#1 will be decreased by 1; if nothing is pointing to it anymore, its memory will be freed.

listb.pop()

Removes the last element from list#2, and returns it; list#2 will be equal to [1, 2, 3, 4]. list#1, if it still exists, will not be changed by this operation.

With only the code above, the list object that you initially stored in lista (list#1) would neither be changed, nor would it exist any more in the memory* when the listb.pop() is executed.


*) though in Jython and other non-CPython implementations the garbage collection might be delayed so it could still be consuming memory.

Upvotes: 4

Daniel
Daniel

Reputation: 42758

In the first line you create a list referenced by lista. In the second line you copy this list and set a reference by listb. In line three, you remove the reference to the list of line one, so the first list is garbage collected. Still the list referenced by listb exists, which is modified in the last line.

Upvotes: 2

Related Questions