为什么print(mylist.append(5))输出None
lst = [2,3,4]
print(lst.append(1))
为什么上面的打印结果是 None 呢?
而 print(lst[1]) 却能正常工作?
相关问题:
2 个回答
-1
是的,这是因为这个函数(list.append)不返回任何东西。如果你打印它的结果,输出的就是 None。
def f1(x):
print(x)
return None
def f2(x):
print(x)
return x
print(f1(2))
>>> 2 # inside the function
>>> None # return value of function
print(f2(2))
>>> 2 # inside the function
>>> 2 # return value of function
0
lst.append 这个方法总是返回 None,这就是为什么 print 打印出来的结果是 None。
如果你想要添加一个元素并打印出最后一个元素,可以这样做:
lst = [2,3,4]
lst.append("foo")
print(lst[-1]) # Prints foo