Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning list to one value in that list

Tags:

python

I have a slight problem understanding the behaviour of lists.

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?

Thank you, Damian

like image 586
Blücher Avatar asked Nov 20 '11 12:11

Blücher


People also ask

Can you += a list?

For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.


2 Answers

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:

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

... and so on. It's turtles all the way down.

like image 195
Bryan Oakley Avatar answered Oct 06 '22 16:10

Bryan Oakley


You are literally inserting a list into itself. The resulting list cannot be printed anymore because it somewhat goes in a circle:

values = [0, 1, 2]
values[1] = values
# so the list now looks like
[0, values, 2]
# so we expand the variable and get
[0, [0, values, 2], 2]
# and so on
[0, [0, [0, values, 2], 2], 2]
# as this will never end instead Python prints 
[0, [...], 2]

So [...] means that the list contains itself.

like image 45
Jochen Ritzel Avatar answered Oct 06 '22 16:10

Jochen Ritzel