Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python memory management for list()

Tags:

python

I'm creating a tuple, and then converting it to a list with the code:

y=("hello","the","world")
y=list(y)

Does python simply mark the objects as now mutable and reachable through the label y, or does it create a complete copy of every object, add these to the new list structure, and then delete the original immutable objects?

Cheers

like image 896
Chris Avatar asked Apr 20 '11 14:04

Chris


2 Answers

During the execution of the line

y = list(y)

the following happens:

  1. The right-hand side gets evaluated. This includes creating a new list object. The list object is filled with the items of the tuple object passed to the constructor. These items are not copied. Rather their reference count is increased, and references to these items are added to the new list object.

  2. The newly created list object is assigned to the name on the left-hand side (y). This includes first unassigning the name, which results in decreasing the reference counter of the tuple object y pointed to before. Since there are no more references to this tuple object, it is deleted. Finally, y is set to point to the new list object.

like image 150
Sven Marnach Avatar answered Oct 01 '22 07:10

Sven Marnach


You can find out by inspecting the id of each object.

Here are the results from my run.

y=("hello","the","world")
id(y), [id(i) for i in y]
(18627040, [21912480, 21964056, 21910304])

y = list(y)
id(y), [id(i) for i in y]
(21905536, [21912480, 21964056, 21910304])

As you can see the objects are the same.

Update: Sven Marnach explains how and why of it perfectly. Just for reference, I did more tests for other types of objects.

For an object

class C: pass
x = (C(), C(), C())
id(x), [id(i) for i in x]
(18626400, [19992128, 19992008, 19991328])
x= list(x)
id(x), [id(i) for i in x]
(21863560, [19992128, 19992008, 19991328])

For a list

z = ([], [], [])
id(z), [id(i) for i in z]
(18627040, [21908016, 21907136, 21908536])
z = list(z)
id(z), [id(i) for i in z]
(18614992, [21908016, 21907136, 21908536])

For a list of lists

p = ([[], []], [[], []], [[], []])
id(p), [[id(i) for i in j] for j in p]
(18627040, [[21919504, 21895808], 
            [21894608, 21895008], 
            [19991008, 19789104]])
p = list(p)
id(p), [[id(i) for i in j] for j in p]
(19800352, [[21919504, 21895808], 
            [21894608, 21895008], 
            [19991008, 19789104]])
like image 32
Praveen Gollakota Avatar answered Oct 01 '22 06:10

Praveen Gollakota