3

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?

sebastianspiegel
  • 445
  • 4
  • 12
  • If the list is an element of itself, it is infinitely recursive, and so impossible to print out in the usual format. – khelwood Aug 28 '15 at 19:19

2 Answers2

2

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.

dsh
  • 12,037
  • 3
  • 33
  • 51
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]
>>> 
larsks
  • 277,717
  • 41
  • 399
  • 399