what does 'a=b=c=[]' do

Eric einazaki668 at yahoo.com
Thu Dec 22 23:27:57 EST 2011


On Dec 21, 5:44 pm, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:

> Yes, you should create your lists before trying to append to them.
>
> But you aren't forced to use a for-loop. You can use a list comprehension:
>
> x = [some_function(a) for a in range(n)]
>
> Notice that here you don't need x to pre-exist, because the list comp
> creates a brand new list, which then gets assigned directly to x.
>
> > Now to my actual question.  I need to do the above for multiple arrays
> > (all the same, arbitrary size).  So I do this:
> >    x=y=z=[]
>
> This creates one empty list object, and gives it three names, x, y and z.
> Every time you append to the list, all three names see the same change,
> because they refer to a single list.
>
> [...]
>
> > Except it seems that I didn't create three different arrays, I created
> > one array that goes by three different names (i.e. x[], y[] and z[] all
> > reference the same pile of numbers, no idea which pile).
>
> Exactly.
>
> > This surprises me, can someone tell me why it shouldn't?
>
> Because that's the way Python works. Python is an object-oriented, name
> binding language. This is how OO name binding works: you have a single
> object, with three names bound to it. The above line is short-cut for:
>
> a = []
> b = a
> c = a
>
> Python does not make a copy of the list unless you specifically instruct
> it to.
>
> > I figure if I
> > want to create and initialize three scalars the just do "a=b=c=7",
>
> That creates a single integer object with value 7, and binds three names
> to it, *exactly* the same as the above.
>
> If you could modify int objects in place, like you can modify lists in
> place, you would see precisely the same effect. But ints are immutable:
> all operations on ints create new ints. Lists are mutable, and can be
> changed in place.
>
> > for
> > example, so why not extend it to arrays.  Also, is there a more pythonic
> > way to do "x=[], y=[], z=[]"?
>
> Well that literally won't work, you can't separate them by commas.
> Newlines or semicolons will work.
>
> Or: x, y, z = [], [], []
>
> Either is pretty Pythonic.
>
> --
> Steven

Thanks to you and Dennis for the quick lesson and tips.  Very helpful
and illuminating.



More information about the Python-list mailing list