the python code section are following lines:
>>> values = [0, 1, 2]
>>> values[1] = values
>>> values
[0, [...], 2]
why the value is [0,[...],2],what is ...? why the value is not [0,[0,1,2],2]?
You created a recursive reference; you replaced the item at index 1 with a reference to whole list.
To display that list now, Python does not recurse into the nested reference and instead displays [...].
>>> values = [0, 1, 2]
>>> values[1] = values
>>> values
[0, [...], 2]
>>> values[1] is values
True
Referencing values[1] is the same thing as referencing values, and you can do so ad infinitum:
>>> values[1]
[0, [...], 2]
>>> values[1][1] is values
True
>>> values[1][1] is values[1]
True
[...] means you self-referenced the variable to itself (cyclic reference):
>>> values = [0, 1, 2]
>>> sys.getrefcount(values) #two references so far: shell and `values`
2
>>> values[1] = values #created another reference to the same object but a cyclic one
>>> sys.getrefcount(values) # references increased to 3
3
>>> values[1] is values # yes both point to the same obejct
True
Now you can modify the object using either values or values[1]:
>>> values[1].append(4)
>>> values
[0, [...], 2, 4]
#or
>>> values[1][1][1].append(5)
>>> values
[0, [...], 2, 4, 5]
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