为什么print(mylist.append(5))输出None

0 投票
2 回答
48 浏览
提问于 2025-04-14 17:41

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

撰写回答