Possible Duplicate:
Python passing list as argument
I looked for many topics about that, but I can’t understand what happen really.
I have this code:
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
and the result is:
[1, 2, 3, 1, 2, 10]
[1, 2, 3]
[2, 3, 4]
I can’t understand how the Lista1 was modified and Lista2 not. However before test the code, I thought that Lista1 and Lista2 would stay unmodified because they are global variables.
When you do
L1.append(elemento)you are calling a method that actually changes the list named by the variableL1. All the other commands setting the values ofL1andL2are actually just creating new names for new variables.This version doesn’t change anything:
While this one does:
However there is a tricky matter with
L += [2]which is not exactly the same asL = L + 2. The Python Language Reference section on Augmented assignment statements explains the difference: