Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What range function does to a Python list?

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.

like image 332
Rahul Avatar asked Apr 03 '16 14:04

Rahul


1 Answers

In python2, ranges are lists.

lists, 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.

like image 174
Karoly Horvath Avatar answered Sep 18 '22 22:09

Karoly Horvath