0

I was doing some experiments following this feature: Hidden features of Python

The used code is:

def f(x = []):
    x.append(x)
    return x

which output is:

>>> f()
[[...]]

I would like to understand what do [...] mean and why it an infinite nested list is produced.

Community
  • 1
  • 1
Blex
  • 156
  • 11

2 Answers2

1

Appending a list to itself would make a loop structure, the [...] means repeating itself infinitely.

yangjie
  • 6,619
  • 1
  • 33
  • 40
0

You have to understand that function defaults are evaluated when the function is first created not when it is run. So to start with, your code is equivalent to this:

X = []
def f(x=X):
    x.append(x)
    return x

If you run it just once, then this is equivalent to this:

X = []
X.append(X)

Which is creating a list and then setting itself as the first element. So since X == X[0] then it follows that X == X[0][0] and X == X[0][0]...[0].

Brendan F
  • 619
  • 3
  • 8