Self-referencing lists

前端 未结 3 1960
刺人心
刺人心 2020-12-11 23:39

Say you do the following:

a = [1]
a[0] = a

You end up with a as equal to [[...]]. What\'s going on here? How doe

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 00:39

    The list contains a reference to itself. The [[...]] is how this is rendered when you print the list.

    The implementation goes out of its way to ensure it doesn't end up in an infinite recursion. It does this by rendering references to objects that are already being printed as [...].

    This makes it work with indirect self-references too:

    >>> a = []
    >>> b = [a]
    >>> a.append(b)
    >>> a
    [[[...]]]
    >>> b
    [[[...]]]
    

    If you are really curious, you could study CPython's source code. In Python 2.7.3, the relevant code is located in Objects/listobject.c.

提交回复
热议问题