creating lists question?

Gandalf gandalf at geochemsource.com
Wed Mar 24 05:49:18 EST 2004


> I must admit I am stumped about one thing though. I originally came up 
> with this (non-)solution to the case where you do know how many lists 
> you need:
>
> aaa, bbb, ccc = ([],) * 3
>
> Unfortunately, this doesn't do what I expected it to do. I thought 
> that the above line would be equivalent to:
>
> aaa, bbb, ccc = ([], [], [])
>
> but in fact they are three names for the same list, equivalent to aaa 
> = bbb = ccc = []
>
> Why is this? Bug or feature?
>
The * operator applied to a tuple will create another tuple consisting 
of the same objects but many times. For example,
(2,3,) *3  

will create (2,3,2,3,2,3)

However, if you do this:

(obj,)*3

then you will get

(obj,obj,obj,)

You will get references to the the same object.  :-)

In your case, what Python does is:

- Calculate the right side = (o,o,o,) where o = [] (e.g. the same object.)
- Then assign it to the right side:

aaa,bbb,ccc = (o,o,o,)   

  G






More information about the Python-list mailing list