Search code examples
pythonlistmethodsmutability

Python function got 2 lists but only changes 1


why does Lista1 get changed but Lista2 doesn't? which methods change directly the list?

def altera(L1, L2):
    for elemento in L2:
        L1.append(elemento)
    L2 = L2 + [4]
    L1[1]= 10
    del L2[0]
    return L2[:]

Lista1 = [1, 2, 3]
Lista2 = [1, 2, 3]

Lista3 = altera(Lista1, Lista2)

print(Lista1)
print(Lista2)
print(Lista3)

Solution

  • L2 = L2 + [4] This statement create new variable.

    If you change this statement to L2.extend([4]) or L2 += [4] then it will change value of L2 which is [2, 3, 4]

    printing id of L2 before and after assignment.

    >>> L2 = [1,2,3]
    >>> id(L2)
    3072769420L    # ID of L2 
    >>> L2 += [4]
    >>> id(L2)
    3072769420L    # Same ID of L2
    >>> L2
    [1, 2, 3, 4]
    >>> L2 = L2+[5]
    >>> id(L2)
    142773548      # New variable which name  is L2