5

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.

lulyon
  • 6,707
  • 7
  • 32
  • 49

4 Answers4

6

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[:]
filmor
  • 30,840
  • 6
  • 50
  • 48
3

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[:]
ovgolovin
  • 13,063
  • 6
  • 47
  • 78
2

You need to copy it:

values[1] = values[:]
Michael
  • 15,386
  • 36
  • 94
  • 143
1
>>> 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 ... ... ...

kiriloff
  • 25,609
  • 37
  • 148
  • 229