0

I can see some Python code below, but I don't know what's the purpose/use of it? Any reply will be appreciated!

r = []
r[:] = [r, r, None]
>>> r
>>> [[...], [...], None]
Edwin
  • 71
  • 1
  • 1
  • 3
  • 4
    We cannot help you without the context of this code. Where does it come from? – Delgan Aug 29 '17 at 06:51
  • As you show it to us, it doesn't make much sense. Context and use-cases are important. – Some programmer dude Aug 29 '17 at 06:53
  • Possible duplicate of [What is the difference between slice assignment that slices the whole list and direct assignment?](https://stackoverflow.com/questions/10155951/what-is-the-difference-between-slice-assignment-that-slices-the-whole-list-and-d) – Nir Alfasi Aug 29 '17 at 07:00

2 Answers2

2
r = []

This is easy. Set r to be a new empty list.

r[:] = [r, r, None]

[r, r, None] is a list that contains two references to the list referenced by r, and a None value.

r[:] = replaces all the elements of the existing list that is referred to by r, with the right hand side of the assignment.

The result is that r refers to a list that contains references to itself.

>>> r
>>> [[...], [...], None]

The ... notation means that Python has spotted an infinite loop, and rather than go down the rat-hole, it just prints ....

The purpose of this code is not clear - my initial reaction is "an entry to the International Obfuscated Python Contest perhaps?"

  • I investigated the code further, It seems it implemented Doubly Circular linked list. r[:] = [r, r, None] is just a initialization, then it made the list like [here](http://www.equestionanswers.com/c/c-doubly-circular-linked-list.php). – Edwin Aug 29 '17 at 11:26
2
>>> r = []
>>> r[:] = [r, r, None] # You do this

You are assigning r to r, kind of circular link

Try accessing 0th index and you will see this

>>> r[0]
[[...], [...], None]
>>> r[0][0]
[[...], [...], None]
>>> r[0][0][0]
[[...], [...], None]

Proof: try printing IDs of r and r[0] and sooo on

>>> id(r[0][0][0])
4508668632
>>> id(r[0][0][0][0])
4508668632
>>> id(r[0][0][0][0][0])
4508668632
naren
  • 14,611
  • 5
  • 38
  • 45