0

I have this code:

a = [1,2,3]
a[1] = a
a # output: [1, [...], 3]
a[1] # output: [1, [...], 3]
a[1][1] # output: [1, [...], 3]

I honestly don't know what I expect those to look like, but I was guessing that a[1] should be the memory address for the object "a".

Can any python master shed some light as to what's going on?

Heavy Breathing
  • 567
  • 6
  • 20
  • How do you expect this to be printed? To print `a`, you have to print one of its inner elements, which is `a`, but to print `a` you need to print one of its inner elements which is `a` and so on.... The interpreter just keeps a set of objects that have been visited while building the string to print, and if there's a circular reference print it as `...` and skip visiting it so the interpreter doesn't blow up. – ggorlen Oct 16 '20 at 00:12
  • 1
    "but I was guessing that a[1] should be the memory address for the object "a"." Why would you guess that? When do memory addresses ever get assigned instead of the object itself? No, that is just how Python represents self-referential lists. If you think about it, the `__repr__` would go in an infinite loop, instead, it short-circuits and puts `...` – juanpa.arrivillaga Oct 16 '20 at 00:14
  • That's just how the repr is defined for self-referencing lists: https://github.com/python/cpython/blob/cf693e537dc8aaa14315a7f59baec4a31d1167d3/Objects/listobject.c#L373 and the detection of such a case is implemented here: https://github.com/python/cpython/blob/cf693e537dc8aaa14315a7f59baec4a31d1167d3/Objects/object.c#L1936-L1949 – wim Oct 16 '20 at 00:20
  • Note that you can and should make your own container types have the same recursion protection quite easily by [decorating your `__repr__` with `@reprlib.recursive_repr()`](https://docs.python.org/3/library/reprlib.html#reprlib.recursive_repr) (optionally passing an argument of some other string to use instead of the default ellipsis). – ShadowRanger Oct 16 '20 at 00:36

0 Answers0