为什么信息没有存储在这个变量中?

时间:2015-07-28 20:54:14

标签: python python-3.x

我有程序:

def append(aList):
    return aList.append(10)

def main():
    mylist = [1, 2, 3]
    newlist = append(mylist)
    print(newlist,",", mylist)

main()

当我运行此程序时,输出为:

None , [1, 2, 3, 10]

为什么变量newlist中没有存储信息?

2 个答案:

答案 0 :(得分:1)

append不会返回值,如here所述。

这可能更符合你想要的,尽管这个例子是相当人为的。

def append(aList):
    aList.append(10)
    return aList

答案 1 :(得分:0)

如上所述append()返回None。 append()可以使用 inplace

所以这是一个解决方案:

from copy import copy

def append(aList):
    aList = copy(aList)
    aList.append(10)
    return aList

def main():
    mylist = [1, 2, 3]
    newlist = append(mylist)
    print(newlist,",", mylist)

main()

<强>输出:

[1, 2, 3, 10] , [1, 2, 3]