Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 540
sebastianspiegel Avatar asked Oct 20 '25 14:10

sebastianspiegel


2 Answers

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]
>>> 
like image 67
larsks Avatar answered Oct 23 '25 05:10

larsks


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.

like image 26
dsh Avatar answered Oct 23 '25 03:10

dsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!