Any other Python flaws?

phil hunt philh at comuno.freeserve.co.uk
Fri Jun 15 13:07:07 CEST 2001


On 15 Jun 2001 00:37:22 -0700, Martin Sandin <msandin at hotmail.com> wrote:
>> ...I got an array with 100 elements, all 0.
>> 
>> I think python is OK here.
>
>Except you didn't =) You got a list of 10 references to a list with 10
>references to the number 0.

No, I didn't. (Replacing 10 with 3 for concision):

   philh:~> python
   Python 2.0 (#1, Jan 19 2001, 17:54:27)
   [GCC 2.95.2 19991024 (release)] on linux2
   Type "copyright", "credits" or "license" for more information.
   >>> array = ([0] * 3) * 3
   >>> array
   [0, 0, 0, 0, 0, 0, 0, 0, 0]
   >>> array[2] = 2
   >>> array
   [0, 0, 2, 0, 0, 0, 0, 0, 0]          


If I'd got a list of lists, it would have looked like:

[[0,0,0], [0,0,0], [0,0,0]]

> That the inner list is a list of
>references to the same object doesn't matter much, 

But it isn't. When I change one value, doesn't change the others.
If i wanted a reference I could say something like:

   >>> a = [1]*3
   >>> b =[a]*3
   >>> b
   [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   >>> b[1][1]=2
   >>> b
   [[1, 2, 1], [1, 2, 1], [1, 2, 1]]
          
Note that if I now say:

   >>> c=a*3
   >>> c
   [1, 2, 1, 1, 2, 1, 1, 2, 1]
   >>> c[2]=3
   >>> c
   [1, 2, 3, 1, 2, 1, 1, 2, 1]   


-- 
##  Philip Hunt                   ##
##  philh at comuno.freeserve.co.uk  ##






More information about the Python-list mailing list