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.
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.
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[:]
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[:]
You need to copy it:
values[1] = values[:]
>>> values = [0, 1, 2]
>>> values[1] = values
you are saying that values[1]
is values
, which is [0, 1, 2]
, with values
instead of 1, and now values
is [0, 1, 2]
, with values
instead of 1, [0, 1, 2]
, with values
instead of 1, [0, 1, 2]
, with values
instead of 1,[0, 1, 2]
, with values
instead of 1, [0, 1, 2]
, with values
instead of 1 ... ... ...