What do ellipsis […] mean in a list?

前端 未结 5 1518
甜味超标
甜味超标 2020-11-22 10:46

I was playing around in python. I used the following code in IDLE:

p  = [1, 2]
p[1:1] = [p]
print p

The output was:

[1, [.         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 11:16

    This is what your code created

    It's a list where the first and last elements are pointing to two numbers (1 and 2) and where the middle element is pointing to the list itself.

    In Common Lisp when printing circular structures is enabled such an object would be printed as

    #1=#(1 #1# 2)
    

    meaning that there is an object (labelled 1 with #1=) that is a vector with three elements, the second being the object itself (back-referenced with #1#).

    In Python instead you just get the information that the structure is circular with [...].

    In this specific case the description is not ambiguous (it's backward pointing to a list but there is only one list so it must be that one). In other cases may be however ambiguous... for example in

    [1, [2, [...], 3]]
    

    the backward reference could either point to the outer or to the inner list. These two different structures printed in the same way can be created with

    x = [1, [2, 3]]
    x[1][1:1] = [x[1]]
    
    y = [1, [2, 3]]
    y[1][1:1] = [y]
    
    print(x)
    print(y)
    

    and they would be in memory as

    enter image description here

提交回复
热议问题