Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:how to understand assignment and reference?

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]?

like image 962
liuzhijun Avatar asked Jun 01 '26 06:06

liuzhijun


2 Answers

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
like image 84
Martijn Pieters Avatar answered Jun 03 '26 21:06

Martijn Pieters


[...] 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]
like image 23
Ashwini Chaudhary Avatar answered Jun 03 '26 21:06

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!