What happens when you append a list to itself? [duplicate]

跟風遠走 提交于 2019-12-31 04:04:10

问题


Suppose I ran the program

x=[]

x.append(x)

print(x)

I get [[...]] as the output. But what does it mean? Is the list storing pointers and then pointing to itself? Or is it copying itself never quite completely? How is this list stored in memory?

Amendment: I'm trying to get my head around how python accomplishes this self reference. If I wanted to design a way of storing lists that allows for self reference, I would store a variable as a pair of values, the data type and value. If the data type is an int then the value represents the integer that is stored but if the data type is a list, I would say the stored value should be a pointer but pointing where? The beginning of the list like in C?


回答1:


Python lists contain references (similar to pointers) to objects. A list can refer to itself. Just don't try and recursively iterate through the list or you will end up with a stack overflow.




回答2:


I think the output you are seeing becomes more clear if you add another element to the list. You have:

>>> x = []
>>> x.append(x)
>>> x
[[...]]

If we append another value to x:

>>> x.append(1)

Then we have:

>>> x
[[...], 1]

Here, [...] is just Python's way of representing the fact that the list is embedded in itself.

And of course:

>>> x[0]
[[...], 1]
>>> x[0][0][0]
[[...], 1]
>>> 


来源:https://stackoverflow.com/questions/32278356/what-happens-when-you-append-a-list-to-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!