为什么"追加('w')"返回None?

Mic*_*ael 1 python python-2.7

这是我的代码:

def list_test(foo):
    bar = foo.append('w')
    return bar

my_input = [7,8,9]
Run Code Online (Sandbox Code Playgroud)

当我运行它:

>>>print list_test(my_input)
None
Run Code Online (Sandbox Code Playgroud)

这是打印输出None.为什么?我该如何解决这个问题?

注意:我需要的输出是:7,8,9,'w'

谢谢.

Rob*_*obᵩ 9

list.append()返回None以强调它是一个变异调用的事实.修改其参数的此类调用通常返回None.创建列表的调用将返回它.

如果list_test返回修改后的列表很重要,那么您的代码可能会更好:

def list_test(foo):
    foo.append('w')
    return foo

my_input = [7,8,9]

>>> print list_test(my_input)
[7, 8, 9, 'w']
>>> print my_input
[7, 8, 9, 'w']
Run Code Online (Sandbox Code Playgroud)

但是,如果我写这篇文章,我会遵循变更调用返回None的约定,并以这种方式编写它:

def list_test(foo):
    foo.append('w')

my_input = [7,8,9]

>>> print list_test(my_input)
None
>>> print my_input
[7, 8, 9, 'w']
Run Code Online (Sandbox Code Playgroud)

最后,如果你想要list_test是非变异的,那就是它应该返回一个新的列表而不是修改它的输入,其中一个可能适合你:

def list_test(foo):
    new_foo = list(foo)
    new_foo.append('w')
    return new_foo

def list_test(foo):
    return foo + ['w']

my_input = [7,8,9]

>>> print list_test(my_input)
[7, 8, 9, 'w']
>>> print my_input
[7, 8, 9]
Run Code Online (Sandbox Code Playgroud)