list.append problem?

Steve Holden sholden at holdenweb.com
Mon Oct 1 17:54:07 EDT 2001


"newgene" <newgene at bigfoot.com> wrote in message
news:a50631f6.0110011345.31523630 at posting.google.com...
> I am a newer of python. I have a problem like this code:
>
> >>> a=b=c=[]
> >>> a.append(1)
> >>> b.append(2)
> >>> c.append(3)
> >>> a
> [1, 2, 3]
> >>> b
> [1, 2, 3]
> >>> c
> [1, 2, 3]
>
> a,b,c become the same, although append method applied seperately.
> It's really strange and unreasonable.
> My python is ActivePython Build 210 running on WinNT.
>
Strange and unreasonable as it may seem, it's classic Python. All three
variables are bound to the same object, so when you change the object (no
matter which name you use) the value you see when you access any of the
names is the same.

However, try
>>> a = []
>>> b = []
>>> c = []
>>> a.append(1)
>>> b.append(2)
>>> c.append(3)

and you will see what you feel is more reasonable behavior: in this case
each variable is bound to a different list, and so changing one of the lists
doesn't affect the values bound to the other variables.

You get used to it after a while, and after your third progam it will seem
the most reasonable thing to do!

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list