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[:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With