python如何从函数返回列表?传递的列表是不可变的?

时间:2012-02-25 06:55:57

标签: python

def insertion_sort(A):
    for j in range(1, len(A)):
        key = A[j]
    i = j - 1
    while (i >= 0) and (A[i] > key):
        A[i+1] = A[i]
        i = i-1
    A[i+1] = key

    return A


print insertion_sort([8, 1, 3, 4, 9, 5, 2])

现在打印:[8, 1, 3, 4, 9, 5, 2]

但我认为,我正在改变列表A,那为什么返回值相同?

2 个答案:

答案 0 :(得分:6)

您当前的缩进代码错误。它应该是这样的,对吧?

def insertion_sort(A):
    for j in range(1, len(A)):
        key = A[j]
        i = j - 1
        while (i >= 0) and (A[i] > key):
            A[i+1] = A[i]
            i = i-1
        A[i+1] = key

    return A

答案 1 :(得分:0)

如前所述,缩进不正确。

列表是可变的!