Why does “delete” mutate the list when called locally?

Possible duplicate:
Understanding the call style of a Python object to pass arguments to a function

I recently came across this:

x = [1,2,3]

def change_1(x):
    x = x.remove(x[0])
    return x

Result:

>>> change_1(x)
>>> x
[2, 3]

I find this behavior unexpected since I thought that everything inside the function does not affect external variables. In addition, I built an example where basically they do the same thing, but without using remove:

x = [1,2,3]

def change_2(x):
    x = x[1:]
    return x

Result:

>>> change_2(x)
[2, 3] # Also the output prints out here not sure why this is
>>> x
[1, 2, 3]

And I get the result that I would expect, the function does not change x.

So it must be something special removethat has an effect. What's going on here?

+3
source share
3 answers

, , , "x". :

def change_1(x):       # the x parameter is a reference to the global 'x' list
    x = x.remove(x[0]) # on the left, though, is a new 'x' that is local to the function
    return x           # the local x is returned

>>> x = [1, 2, 3]
>>> y = change_1(x)    # assign the return value to 'y'
>>> print y
None                   # this is None because x.remove() assigned None to the local 'x' inside the function
>>> print x
[2, 3]                 # but x.remove() modified the global x inside the function

def change_2(x):
    x = x[1:]          # again, x on left is local, it gets a copy of the slice, but the 'x' parameter is not changed
    return x           # return the slice (copy)

>>> x = [1, 2, 3] 
>>> y = change_2(x)
>>> print x
[1, 2, 3]             # the global 'x' is not changed!
>>> print y
[2, 3]                # but the slice created in the function is assigned to 'y'
+7

, n q.

. x x "". , x, change_1(), , . x.remove() , : " , x. . lhs. y=0; x=y . . " x" [1, 2. 3] , y.

+2

x . , . . , .

, python , .

+1
source

All Articles