list.append problem?

Bob Parnes rparnes at megalink.net
Tue Oct 2 09:36:07 EDT 2001


Steve Holden wrote:

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

As another newcomer I discovered this on my own. What is confusing, I 
think, is that it seems to apply only to empty objects. For example

>>> a = b = [1, 2. 3]
>>> a = [4, 5, 6]
>>> b
[1, 2, 3]
>>> a.append(7)
>>> a
[4, 5, 6, 7]
>>> b
[1, 2, 3]

In this case a and b are not bound to the same object. It seems to me that 
python treats empty objects differently from assigned objects. Or something 
like that, I'm probably not articulating it well.

-- 
Bob Parnes
rparnes at megalink.net



More information about the Python-list mailing list