When you do L1.append(elemento)
you are calling a method that actually changes the list named by the variable L1
. All the other commands setting the values of L1
and L2
are actually just creating new names for new variables.
This version doesn’t change anything:
def altera(L1, L2):
for elemento in L2:
# create a new list and assign name L1
L1 = L1 + [elemento]
# create a new list and assign name L2
L2 = L2 + [4]
return L2
Lista1 = [1,2,3]
Lista2 = [1,2,3]
Lista3 = altera(Lista1, Lista2)
print Lista1
print Lista2
print Lista3
While this one does:
def altera(L1, L2):
for elemento in L2:
# Call method on L1 that changes it
L1.append(elemento)
# Call method on L2 that changes it
L2.append(4)
# Change object pointed to by name L1 -- Lista1
L1[-1] = 10
# Change object pointed to by name L2 -- Lista2
del L2[0]
return L2[:]
Lista1 = [1,2,3]
Lista2 = [1,2,3]
Lista3 = altera(Lista1, Lista2)
print Lista1
print Lista2
print Lista3
However there is a tricky matter with L += [2]
which is not exactly the same as L = L + 2
. The Python Language Reference section on Augmented assignment statements explains the difference:
An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.”