A difficulty with lists

Chris Kaynor ckaynor at zindagigames.com
Mon Aug 6 16:12:38 EDT 2012


On Mon, Aug 6, 2012 at 12:50 PM, Mok-Kong Shen <mok-kong.shen at t-online.de>wrote:

> I ran the following code:
>
> def xx(nlist):
>   print("begin: ",nlist)
>   nlist+=[999]
>

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.


>   print("middle:",nlist)
>   nlist=nlist[:-1]
>

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.

Either of the following will produce the result you are expecting:
nlist.pop() # Pops the last item from the list. More efficient and clearer
than the following:
nlist[:] = nlist[:-1] # Assigns the entire contents of the list to all but
the last item of the list.


>   print("final: ",nlist)
>
> u=[1,2,3,4]
> print(u)
> xx(u)
> print(u)
>
> and obtained the following result:
>
> [1, 2, 3, 4]
> begin:  [1, 2, 3, 4]
> middle: [1, 2, 3, 4, 999]
> final:  [1, 2, 3, 4]
> [1, 2, 3, 4, 999]
>
> As beginner I couldn't understand why the last line wasn't [1, 2, 3, 4].
> Could someone kindly help?
>

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.


>
> M. K. Shen
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120806/d7d8789c/attachment.html>


More information about the Python-list mailing list