Surprising output of Python program
I am just started learning Python am getting bit confused after seeing the output of following program:
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Values inside the function: [1, 2, 3, 4]
[10, 20, 30]
Why is Value开发者_Python百科s outside the function: [10, 20, 30]
, and not [1, 2, 3, 4]
since we are passing the argument to the function by reference?
Works for me, with proper indentation:
def changeme(mylist):
mylist.append([1, 2, 3, 4])
print "Values inside the function: ", mylist
mylist = [10, 20, 30]
changeme(mylist)
print "Values outside the function: ", mylist
Output:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Note that altough semicolons are permitted at the end of the line, their use is discouraged because they serve no purpose and make the code look less clean. Also, you're probably looking for the extend
method of mylist instead of append
:
>>> mylist = [10, 20, 30]
>>> mylist.extend([1, 2, 3, 4])
>>> mylist
[10, 20, 30, 1, 2, 3, 4]
Re: update
In the updated changeme
function you're discarding your reference to mylist, and replacing it with a reference to the new list you've just created. If you keep a reference to the old list, it will stay the same. This should illustrate the point:
def changeme(mylist):
myref = mylist
mylist = [1, 2, 3, 4]
print "myref: ", myref
print "mylist: ", mylist
Output:
myref: [10, 20, 30]
mylist: [1, 2, 3, 4]
To achieve the result you want, you use the python slice notation:
def changeme(mylist):
mylist[:] = [1,2,3,4]
By assigning a value, you are defining a new list, not updating the old one.
You can check by using the id()
function on them.
mylist
inside the function is a local variable. If you bind a new value to a local variable then you only have only changed the binding for the local variable. That won't affect any other variables that happen to be bound to the same object.
If you had mutated the object itself, e.g. by appending to the list, that would have been visible to anything using that same object.
精彩评论