6

My lecturer has set several questions on python, and this one has got me confused, I dont understand what is happening.

x = [[]]
x[0].extend(x)

Python tells me, after running this that x is [[...]], what does the ... mean?

I get even more confused when the result of the following is just [[]]

y = [] # equivalent to x[0]
x = [[]]
y.extend(x)

If y is calculated to be [[]] shouldn't x be calculated to simply being [[[]]]?

What is extend doing? and what does the ... mean?

Rob Murray
  • 1,773
  • 6
  • 20
  • 32
CGA1123
  • 132
  • 7

1 Answers1

6

The ... indicates that the list contains a recursive loop, i.e., at some level something contains itself. This is because you extended x with x, so you essentially put x inside itself.

There is no ... in the second example because y is a distinct object. Although it happens to be equal to x[0] in that both are empty lists, they are not the same empty list.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • So by extending `x[0]` with `x`, its creating a reference to `x` at `x[0]`, rather than copying the data that `x` contains to `x[0]`? is that right? – CGA1123 Nov 29 '15 at 18:54
  • 1
    @CGA1123: Basically, yes. (More specifically, it is creating a reference to `x[0]` inside the list at `x[0]`, since `extend` adds the contents of its argument, not the argument itself. But you are right that it is creating a reference to the same object, not copying data, and that is the key.) – BrenBarn Nov 29 '15 at 18:57