PTF PTF - 2 months ago 9
Python Question

Difference between local and global variables?


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.

Answer

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.”