help with something that ought to be simple

Emile van Sebille emile at fenx.com
Wed Oct 24 22:26:21 EDT 2001


"Matthew Nobes" <manobes at fraser.sfu.ca> wrote in message
news:Pine.GSO.4.30.0110241644520.26688-100000 at fraser.sfu.ca...
<snip>
>
> Now here comes the problem.  I want to add some more stuff to the
> output.  Here's what I try to do:
>
>     temp=[]
>     for i in output[2:]:
>         temp.append(i)

This appends references to the objects in output[2:]
and probably wants to be temp.append(i[:]) so that
a reference to a new copy of the object is pointed to.

>
>     for i in temp:

This iterates through i....

>         i[rho-1]=i[rho-1]-1

and changes the objects referred to.  Note that at this point,
the objects referred to have changed, and that references to
these changed objects are held in output and temp.

>
>     for i temp:
>         output.append(i)

this appends the object references in temp to output.

Most of what python does is bind names with objects.  When
the objects are mutable (as a list is), changes to the underlying
object does not cause a new name binding to occur.  Consider:

L = [1,2,3]
# a new name L has been bound to a new list object [1,2,3]
L1 = L
# a new name L1 has been bound to the list object [1,2,3]
# and that L and L1 now refer to the same list object.
L[1] = 0
# element 1 of the list object pointed to by L is changed to a 0


HTH,


--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list