Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

infinite assignment in python list? [duplicate]

I've come cross this question. Code:

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

The result I expect is:

[0, [0, 1, 2], 2]

Is this an infinite assignment for python list? What is behind the scene?

Thanks.

like image 742
lulyon Avatar asked Jul 20 '13 14:07

lulyon


2 Answers

You have a recursive list there. values[1] is a reference to values. If you want to store the value of values you need to copy it, the easiest way to do so is

values[1] = values[:]
like image 193
filmor Avatar answered Sep 27 '22 20:09

filmor


You put the same list as the second element inside itself. So the second element of the internal list is itself again.

You need to copy initial list to avoid recursion:

>>> values[1] = values[:]
like image 42
ovgolovin Avatar answered Sep 27 '22 21:09

ovgolovin