A difficulty with lists

Madison May worldpeaceagentforchange at gmail.com
Thu Aug 16 09:46:04 EDT 2012


On Wednesday, August 15, 2012 8:21:22 PM UTC-4, Terry Reedy wrote:
> On 8/15/2012 5:58 PM, Rob Day wrote:
> 
> Yeah, my apologies for any confusion I created.  Although I suppose my explanation would be somewhat true for immutable objects since they can't be modified in-place (any modification at all would cause the creation of a new immutable object right?), I now understand that it is completely and totally wrong for mutable objects.  

Thanks for the in-depth explanations, Terry and Rob. I feel like I have a much more solid grasp of what's going on behind the scenes after your analysis. 
> 
>  > Madison May wrote:
> 
> >     The list nlist inside of function xx is not the same as the variable
> 
> >     u outside of the function:  nlist and u refer to two separate list
> 
> >     objects.  When you modify nlist, you are not modifying u.
> 
> >     <http://mail.python.org/mailman/listinfo/python-list>
> 
> 
> 
> This is confused and wrong. The parameter *name* 'nlist' of function xx 
> 
> is not the same as the *name* 'u' outside the function. The call xx(u) 
> 
> binds nlist to the same object that u is bound to. At that point, the 
> 
> two name *are* bound to the same list object. The statement 
> 
> "nlist+=[999]" dodifying nlist *does* modify u. The subsequent 
> 
> assignment statement "nlist=nlist[:-1]" rebinds 'nlist' to a *new* list 
> 
> object. That new object gets deleted when the function returns. So the 
> 
> rebinding is completely useless.
> 
> 
> 
> This sequence, modifying the input argument and then rebinding to a new 
> 
> object, is bad code.
> 
> 
> 
> > Well - that's not quite true. Before calling the function, u is [1, 2,
> 
> > 3, 4] - but after calling the function,  u is [1, 2, 3, 4, 999]. This is
> 
> > a result of using 'nlist += [999]' - the same thing doesn't happen if
> 
> > you use 'nlist = nlist+[999]' instead.
> 
> >
> 
> > I'm not completely aware of what's going on behind the scenes here, but
> 
> 
> 
> you got it right.
> 
> 
> 
> > I think the problem is that 'nlist' is actually a reference to a list
> 
> > object - it points to the same place as u.
> 
> 
> 
> Calling a python function binds parameter names to argument objects or 
> 
> (for *args and **kwds parameters) a collection based on argument objects.
> 
> 
> 
> > When you assign to it within
> 
> > the function, then it becomes separate from u - which is why nlist =
> 
> > nlist+[999] and nlist = nlist[:-1] don't modify u - but if you modify
> 
> > nlist in place before doing that, such as by using +=, then it's still
> 
> > pointing to u, and so u gets modified as well.
> 
> 
> 
> 
> 
> -- 
> 
> Terry Jan Reedy




More information about the Python-list mailing list