<div class="gmail_quote">On Mon, Aug 6, 2012 at 12:50 PM, Mok-Kong Shen <span dir="ltr"><<a href="mailto:mok-kong.shen@t-online.de" target="_blank">mok-kong.shen@t-online.de</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
I ran the following code:<br>
<br>
def xx(nlist):<br>
print("begin: ",nlist)<br>
nlist+=[999]<br></blockquote><div><br></div><div>This is modifying the list in-place - the actual object is being changed to append 999. This can happen because lists are mutable data types in Python, for some other data types (such as integers), this line will copy the integer, increment it, then set the name back to the new value.</div>
<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
print("middle:",nlist)<br>
nlist=nlist[:-1]<br></blockquote><div><br></div><div>Here, you are making a new list, containing all but the last item of the list, then assigning that new list to the name nlist. This does not mutate the passed-in object, just reassigns the name in the local namespace. As an alternative, you can use the list mutation methods, namely pop, to modify the list in place here instead. You could also using a slice assignment to assign to the pre-exisitng list for similar effect.</div>
<div><br></div><div>Either of the following will produce the result you are expecting:</div><div>nlist.pop() # Pops the last item from the list. More efficient and clearer than the following:</div><div>nlist[:] = nlist[:-1] # Assigns the entire contents of the list to all but the last item of the list.</div>
<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
print("final: ",nlist)<br>
<br>
u=[1,2,3,4]<br>
print(u)<br>
xx(u)<br>
print(u)<br>
<br>
and obtained the following result:<br>
<br>
[1, 2, 3, 4]<br>
begin: [1, 2, 3, 4]<br>
middle: [1, 2, 3, 4, 999]<br>
final: [1, 2, 3, 4]<br>
[1, 2, 3, 4, 999]<br>
<br>
As beginner I couldn't understand why the last line wasn't [1, 2, 3, 4].<br>
Could someone kindly help?<br></blockquote><div><br></div><div>The basic concept is that Python uses a pass-by-object system. When you call a function with an object, a reference to that object gets passed into the function. Mutations of that object will affect the original object, but you can assign new objects to the same name as the parameter without affecting the caller.</div>
<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
M. K. Shen<span class="HOEnZb"><font color="#888888"><br>
-- <br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/<u></u>mailman/listinfo/python-list</a><br>
</font></span></blockquote></div><br>