strange list behaviour in 2.1.1

Alex Martelli aleaxit at yahoo.com
Mon Aug 6 10:42:38 EDT 2001


"Adrian Smith" <adrian_p_smith at yahoo.com> wrote in message
news:b9ae8e0f.0108050713.16408c16 at posting.google.com...
> There is a mysterious thing. I wish to take a string from the end of
> one list to the beginning of another, as one might. If I do it
> interactively by hand, with two lists called 'first' and 'second':
>
> >>> second = [first[-1]] + second
> >>> del first[-1]
>
> ...it works fine, but if I put it in a procedure, and call it with the
> parameters 'first' and 'second':
>
> def overflow(firstlist, secondlist):
>     secondlist = [firstlist[-1]] + secondlist
>     del firstlist[-1]
>
> ...the last element of 'first' gets deleted, but 'second' remains
> unaltered. Is there some strange aspect of list assignment I'm
> overlooking here?

No, what you're overlooking is rather one of the most fundamental
aspects of Python: its simple and uniform rules on objects, variable
bindings, and scope.  The effbot has a nice essay on this (dunno if
www.effbot.org is back online yet).

Whether a function rebinds its local variables or not is never going
to affect anything outside the function.  An argument is a local
variable.  Therefore, whether a function rebinds its arguments or
not is never going to affect anything outside the function, and in
particular not the value that was originally passed -- that value
CAN be affected, but not by rebinding a local variable that was
bound to it (rebinding a variable never affects the object that
was previously bound to the variable) -- and NOT the caller's
variable (if any) that was used to pass that value.

Rather than rebinding secondlist, you should be mutating it:
    secondlist[:] = [firstlist[-1]] + secondlist
or more simply:
    secondlist[0:0] = firstlist[-1:]
or equivalently:
    secondlist.insert(0, firstlist[-1])

NOW, since you're modifying the OBJECT (NOT just rebinding a
variable that happens to start out bound to the object), the
caller will see your modifications.


Alex






More information about the Python-list mailing list