a = a[0] = [['Is this information lost?']]
print(a)
Is there any way to gain the string again?
If not, how is this memory-wise handled?
a = a[0] = [['Is this information lost?']]
print(a)
Is there any way to gain the string again?
If not, how is this memory-wise handled?
This example is a bit more illustrative of what's going on:
>>> b = [1, 2]
>>> print(id(b))
22918532837512
>>> a = a[0] = b
>>> print(a)
[[...], 2]
>>> print(id(a))
22918532837512
>>> print(id(a[0]))
22918532837512
>>> print(b)
[[...], 2]
>>> print(id(b))
22918532837512
It is important to understand here that =
is not formally an operator in Python, but rather a delimiter, part of the syntax for assignment statements. In Python, unlike in C or C++, assignments are not expressions. Multi-assignment statements such as x = y = z
are directly accommodated by assignment-statement syntax, not as a consequence of using a single assignment as an expression. A multi-assignment specifies that the value(s) being assigned should be assigned to each target (list), so that x = y = z
is equivalent to
x, y = z, z
Except that z
is evaluated only once. Python does not define the order in which the targets are assigned, but CPython does it left-to-right, so that the above works about the same as
x = z
y = z
except, again, for the multiple evaluation of z
.
And with that, we can understand the original statement. This:
a = a[0] = [['Is this information lost?']]
works like
temp = [['Is this information lost?']]
a = temp
a[0] = temp
del temp
, except that it does not involve a temporary name binding for the target list. Indeed, it should be clear that the previous is also equivalent to this, which is how I imagine most people would write it:
a = [['Is this information lost?']]
a[0] = a
Thus, to answer the original question, the string 'Is this information lost?'
was never accessible other than via the list, so the assignment to a[0]
leaves no name binding through which the string can be reached. The string is indeed lost at that point, in that sense. Python will continue to track it, however, until it is garbage collected.
As far as I can tell, a
is a circular structure -- a list whose one and only element is itself.
>>> len(a)
1
>>> a
[[...]]
>>> len(a[0])
1
>>> a[0]
[[...]]
There is no longer any reference to the string, and hence no way to recover it from the Python interpreter. It should also therefore have been garbage-collected and no longer be in memory (although this is not guaranteed, and it may still be cached but inaccessible).