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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Dec 21 18:44:53 EST 2011


On Wed, 21 Dec 2011 14:25:17 -0800, Eric wrote:

> Is it true that if I want to create an array or arbitrary size such as:
>    for a in range(n):
>       x.append(<some function...>)

x is not defined, so you will get a NameError unless by some lucky fluke 
something else has created x AND it happens to be a list. Either way, it 
is unlikely to do what you want.


> I must do this instead?
>    x=[]
>    for a in range(n):
>       x.append(<some function...>)

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



More information about the Python-list mailing list