My exercise question is:
Draw a memory model showing the effect of the following statements:

values = [0, 1, 2]
values[1] = values

My thinking was that executing these statements will change the list to something like this [0, [0, 1, 2], 3]
, in other words second statement will append the second value in the list(1) but when I execute these statements and then print out the list in Python shell (3.2) I get following result:

[0, [...], 2]

Something has happened to second entry but I’m not sure exactly what, can someone explain what has happened?

3 Answers
3

You've created a recursive data structure. The second element in the list is a reference to the list itself. When you print this out, normally you would expect to see the original list in the second place, as you suggest in your question.

However, you aren't inserting a copy of the original list, you are inserting a reference to the actual list. So, the second element must print out the whole list. But, the second element of this second element is itself a reference to the list, so when it prints its second element, .... Python gracefully handles this by displaying [...] since the only other solution is to present an infinite set of nested lists.

Imagine it this way: after your assignment to values[1], your list can be thought of to look like this:

[0, <pointer to itself>, 2]

Of course, <pointer to itself>, when printed out, looks like:

[0, <pointer to itself>, 2]

When you put those together, you get:

[0, [0, <pointer to itself>, 2], 2]

But of course, to print that innermost <pointer to itself> it, too, must be printed:

I'm down-voting because this doesn't answer the question. The question isn't how to store a copy of a list in the list. The question is, "explain what happens when you set an element in a list to be a reference to itself". This answer offers no explanation, only a workaround. While what you say is very useful advice, it isn't useful in the context of this question.
–
Bryan OakleyNov 20 '11 at 12:54

1

@Bryan Oakley: although it doesn't answer the original question, this is the only entry which actually tells you how to do it, and for that pragmatic approach definitely deserves an upvote.
–
Karoly HorvathNov 21 '11 at 10:02