Python 附加将使我的列表变为非类型

Python 附加将使我的列表变为非类型,python,mutators,Python,Mutators,在Python Shell中,我输入: aList = ['a', 'b', 'c', 'd'] for i in aList: print(i) 得到 a b c d Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> for i in aList: TypeError: 'NoneType' object is

在Python Shell中,我输入:

aList = ['a', 'b', 'c', 'd']  
for i in aList:  
    print(i)
得到

a  
b  
c  
d  
Traceback (most recent call last):  
  File "<pyshell#22>", line 1, in <module>  
    for i in aList:  
TypeError: 'NoneType' object is not iterable  
但当我尝试时:

aList = ['a', 'b', 'c', 'd']  
aList = aList.append('e')  
for i in aList:  
    print(i) 
得到

a  
b  
c  
d  
Traceback (most recent call last):  
  File "<pyshell#22>", line 1, in <module>  
    for i in aList:  
TypeError: 'NoneType' object is not iterable  
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
对于我来说:
TypeError:“非类型”对象不可编辑

有人知道发生了什么事吗?如何修复/绕过它?

list.append
是一种修改现有列表的方法。它不返回新列表——它返回
None
,就像大多数修改列表的方法一样。只需执行
aList.append('e')
,您的列表就会添加元素。

删除第二行
aList=aList.append('e')
,只使用
aList.append('e')
,这应该可以解决该问题。

通常,您想要的是公认的答案。但是,如果您想要覆盖该值并创建一个新列表(在某些情况下是合理的^),您可以使用“splat运算符”,也称为列表解包:

aList = [*aList, 'e']
#: ['a', 'b', 'c', 'd', 'e']
或者,如果需要支持python 2,请使用
+
运算符:

aList = aList + ['e']
#: ['a', 'b', 'c', 'd', 'e']


^在许多情况下,您希望避免使用
.append()
进行变异的副作用。首先,假设您希望将某个内容附加到作为函数参数的列表中。无论是谁在使用这个函数,都可能不希望他们提供的列表会被更改。使用类似的方法可以使函数不返回任何内容。

而且由于它不返回任何内容,因此如果执行赋值,您会将aList设置为None,这就是为什么会出现错误。所有函数都会返回一些内容:)true-但有时会返回一些内容
None
。但是
None
真的很重要吗?我头疼@kindall:“不返回任何东西”应该是“实际上,如果方法没有
return
语句并且隐式返回
None
,则情况相同”。和。变异对象的方法几乎从不返回值,pop是一个显著的例外