I am not able to figure out what is happening here. Appending reference to range
function is kind of creating a recursive list at index 3
.
>>> x = range(3)
[0, 1, 2]
>>> x.append(x)
[0, 1, 2, [...]]
>>> x[3][3][3][3][0] = 5
[5, 1, 2, [...]]
Whereas, when I try this:
>>> x = range(3)
[0, 1, 2]
>>> x.append(range(3))
[0, 1, 2, [0, 1, 2]]
I can easily deduce the reason for the second case but not able to understand what appending reference to range
function is doing to the list appended.
In python2, range
s are list
s.
list
s, and most of the things in python are objects with identities.
li = [0,1]
li[1] = li # [0, [...]]
# ^----v
id(li) # 2146307756
id(li[1]) # 2146307756
Since you're putting the list inside itself, you're creating a recursive data structure.
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