2

I've run into this unseen list object, when I tried to play with list append, and I've searched hard but unable to find much information. So this is what's happening:

L = ['dinosaur']
L.append(('theropoda', L))
print(L)
# ['dinosaur', ('theropoda',   [...])]

Questions - what's the [...] means here? Thanks.

  • 1
    Does this answer your question? https://www.sololearn.com/Discuss/1856497/python-append-a-list-to-the-same-list – Seth Feb 07 '21 at 03:47
  • 3
    I believe it indicates a circular list, you're appending L to L – depperm Feb 07 '21 at 03:48
  • Thanks for the tips. Glad there are experts here to help. Do you want to put it in the Answer so I can vote it? (BtW - is there official doc.?) –  Feb 07 '21 at 03:53
  • 3
    Python prints a [...] whenever it detects a cycle in the object. when a collection object contains a reference to itself... 'and it try to avoid the stuck in an infinite loop. Good question. – Daniel Hao Feb 07 '21 at 03:56
  • this question needs a better title – Vishal Singh Feb 07 '21 at 05:09

1 Answers1

2

As mentioned in the comments, Python will not attempt to include a circular/recursive reference in the representation of a list.

It would appear that the __repr__ function (also used by lists to create the string for printing) is implemented via reprlib with recursive support. Without it, you would end up with a RecursionError as to output the list, Python must include the nested version of the list, which also needs the nested version, and so on. Instead, it outputs the special value of ... which indicates to you that it is a recursive reference.

Scott Stevens
  • 2,546
  • 1
  • 20
  • 29