Python memory management for list ()

I create a tuple and then convert it to a list with code:

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

Does python point to objects that are now modifiable and reachable via the y label, or create a full copy of each object, add them to the new list structure, and then delete the original immutable objects?

Greetings

+7
source share
3 answers

At runtime

 y = list(y) 

the following happens:

  • The right side is evaluated. This includes creating a new list object. The list object is populated with elements of the tuple object passed to the constructor. These items are not copied. Rather, their reference count is incremented, and links to these items are added to the new list object.

  • The created list object is assigned a name on the left side ( y ). This includes the first naming, which reduces the reference counter of the tuple y object specified earlier. Since there are no more links to this tuple, it is deleted. Finally, y set to a new list object.

+14
source

You can find out by checking the id each object.

Here are the results of my launch.

 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 it is beautiful. For reference, I did more tests for other types of objects.

For 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 the 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]) 

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]]) 
+10
source

Python does not perform deep copying unless you explicitly specify it. Thus, the result will be a new modified list containing references to the same objects as those that you put in the tuple.

Note that the objects in the tuple themselves are always mutable. This is just a tuple of strings that is immutable, i.e. You cannot add / remove objects to a tuple, but you can always get and modify objects inside a tuple.

+3
source

All Articles