Tuple assignment and generators?

Larry Bates larry.bates at websafe.com
Thu May 4 14:59:28 EDT 2006


Just wrote:
> In article <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d at comcast.com>,
>  Larry Bates <larry.bates at websafe.com> wrote:
> 
>> While I have never needed anything like this in my 5 years of Python
>> programming, here is a way:
>>
>> a,b,c = 3*[0]
>> q,r,s,t,u,v = 6*[0]
> 
> This is (IMO) fairly idiomatic:
> 
>    a = b = c = 0
>    q = r = s = t = u = v = 0
> 
> Just

You must be careful with this as they all point to
exactly the same object.  Example:

>>> q = r = s = t = u = v = 0
>>> id(q)
3301924
>>> id(r)
3301924
>>> id(s)
3301924
>>>

Notice that all of them point to exactly the same object,
not 6 copies of zero which is "probably" what the poster
was thinking.

Most of the time when I see this, it is because people are
thinking of variables having values which is mostly a
carry-over from old Fortran/Cobol/Basic programming ideas.
In python variables are pointers to objects.  Objects could
be values, but they are not placeholders where you store
stuff.

I read on this list (quite frequently) that people
think they are getting 6 separate variables each with
a zero stored in them.  They are not.  They are getting
six pointers that all point to an integer zero (IMHO it
would be a rather odd application for a programmer
to want this).  Here is where multiple assignments
causes problems for beginners:

>>> a=[]
>>> b=c=a
>>> a.append(6)
>>> b
[6]

What??  'b' should contain an empty list, right?  Nope.
a, b, and c all point to the SAME list just like the
poster's  q, r, s, t, u, v all point to the SAME zero.

What they meant to write was:

c=a[:]  # Shallow copy of list
b=a[:]

My rule, don't do it unless you know exactly why you
want to do it.  It will trip you up at some point and
be VERY hard to find.

-Larry Bates



More information about the Python-list mailing list