Python — Russell's paradox (lists,not sets)

2020-07-22 09:04发布

问题:

I know that one can create lists within lists. But how many, exactly can I fit in one. I tried this in the IPython console:

In [1]: Alist = [1]

In [2]: Alist.append(Alist)

In [3]: Alist
Out[3]: [1, [...]]

In [4]: Alist[1]
Out[4]: [1, [...]]

In [5]: Alist[1][1]
Out[5]: [1, [...]]

In [6]: Alist[1][1][1]
Out[6]: [1, [...]]

Now I could go on forever trying to access Alist[1][1][1][1]...[1], But how is this possible? Also, how come my machine hasn't run out of memory with this? I use Python2.7 on Ubuntu 16.04 if it helps.

回答1:

There is only one object of finite size here:

You first create a list object with one element [1], and then you create a reference to that object that you call Alist. When you append Alist to "istelf", you really just append the reference to your object to the object itself. You now have a list object with two elements: 1 and a reference to itself. No infinite memory involved here.

Try this to convince yourself:

Alist = [1]
Alist.append(Alist)
Alist[1][0] = 0
Alist[0]