在 Python3.2 我正在尝试做一个列表:
>> ls = 1, 2, 3
>> ls
(1, 2, 3)
>> ls.append(4)
使用最后一个命令,我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
为什么是这样?我该如何解决?谢谢你的时间
列表的语法是[1, 2, 3].
(1, 2, 3)是一个元组。
列表是可变的,但元组是不可变的。也就是说,元组在创建后就不能被修改(这就是你不能修改它们的原因append)。
这个答案对您何时使用另一个具有很好的洞察力。