A difficulty with lists

Rob Day robert.day at merton.oxon.org
Wed Aug 15 17:58:34 EDT 2012


> 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>


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 I
think the problem is that 'nlist' is actually a reference to a list object
- it points to the same place as u. 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.

So, for example:

>>> def blank_list(nlist):
...     nlist[:] = [] # modifies the list in-place
...
>>> u
[1, 2, 3, 4]
>>> blank_list(u)
>>> u
[] # u has been changed by our change to nlist!

But if we change it so that it assigns to nlist rather than modifying it:

>>> def dont_blank_list(nlist):
...     nlist = [] # creates a new list object rather than modifying the
current one
...
>>> u = [1, 2, 3, 4]
>>> u
[1, 2, 3, 4]
>>> dont_blank_list(u)
>>> u
[1, 2, 3, 4] # u is completely unaffected!
-- 
Robert K. Day
robert.day at merton.oxon.org




-- 
Robert K. Day
robert.day at merton.oxon.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120815/e2d387ba/attachment.html>


More information about the Python-list mailing list