为什么 Python 列表没有范围限制(而整数有)?

Why Python list doesn't have scope limitation (while integer has)?

我的意思是,对于一个整数:

>>> a = 2
>>> def b():
...     a += 1
...
>>> b()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in b
UnboundLocalError: local variable 'a' referenced before assignment

对于列表(或者说对于列表元素):

>>> a = [0]
>>> def b():
...     a[0] += 1
...
>>> b()
>>> a[0]
1

在带有 int 的示例中,Python 试图在函数 b() 中将某些内容分配给 a,因此它将 a 标识为"local" 函数中的变量。由于变量 a 尚未定义,解释器会抛出错误。

在带有 list 的示例中,Python 并未尝试将任何内容分配给 a,因此解释器将其识别为 "global" 变量。是的,它正在修改列表中的值,但是对名为 a 的列表对象的引用没有改变。