0

I'm reading on Python variables, objects and references, and stumbled on the notion of circular reference. The book presents an example:

L = [1,2]
L.append(L)
L

I tried on Python, the result is:

[1,2, [...]]

I kind of understand circular reference but not sure how Python generates this result, I mean, where it starts, where it goes on and how it ends up with this list. Very much appreciate if any one could help explain this.

  • 1
    Related question [here](https://stackoverflow.com/questions/17160162/what-do-ellipsis-mean-in-a-list). Are you asking how Python print internally recognizes that it's circular? – jarmod Aug 31 '22 at 14:30
  • 2
    `L.__repr__` simply detects that the list element it has to produce a string for is `L`, and use `[...]` instead of recursively calling `L.__repr__`. – chepner Aug 31 '22 at 14:35
  • Something like `x += '[...]' if x is self else repr(x)` in the definition `def __repr__(self): ...`. – chepner Aug 31 '22 at 14:37
  • (It's a little more complicated, because it can detect deeper cycles as well, such as `L = [1, 2]; C = [3, 4, L]; L.append(L)`.) – chepner Aug 31 '22 at 14:39

0 Answers0