Tuple assignment and generators?
larry.bates at websafe.com
Thu May 4 20:59:28 CEST 2006
> 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*
>> q,r,s,t,u,v = 6*
> This is (IMO) fairly idiomatic:
> a = b = c = 0
> q = r = s = t = u = v = 0
You must be careful with this as they all point to
exactly the same object. Example:
>>> q = r = s = t = u = v = 0
Notice that all of them point to exactly the same object,
not 6 copies of zero which is "probably" what the poster
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
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:
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
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.
More information about the Python-list