Confusing […] List in Python: What is it?

前端 未结 9 2168
傲寒
傲寒 2020-11-29 10:52

So I was writing up a simple binary tree in Python and came across [...]

I don\'t believe this to be related to the Ellipsis object, more it seems to have something

9条回答
  •  感动是毒
    2020-11-29 11:45

    I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however

    Look at the following code:

    >>> a = [0]
    >>> a.append(a)
    >>> print a
    [0, [...]]
    

    How is Python supposed to print a? It is a list that contains a zero and a reference to itself. Hence it is a list that contains a zero and a reference to a list

    [0, [...]]
    

    which in turn contains a zero and a reference to a list

    [0, [0, [...]]]
    

    which in turn contains a zero and a reference to a list, and so on, recursively:

    [0, [0, [0, [...]]]]
    [0, [0, [0, [0, [...]]]]]
    [0, [0, [0, [0, [0, [...]]]]]]
    ...
    

    There is nothing wrong with the recursive data structure itself. The only problem is that it cannot be displayed, for this would imply an infinite recursion. Hence Python stops at the first recursion step and deals with the infinity issue printing only the ellipsis, as was pointed out in previous answers.

提交回复
热议问题