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
During the execution of the line
y = list(y)
the following happens:
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.
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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With