[Tutor] Re: Multiple Assignments...

Praveen Pathiyil ppathiyi@cisco.com
Thu, 10 May 2001 16:20:09 +0530


Hi Danny,
        Thx for the explanation. I am just prolonging the discussion.....

a,b = b,a

In your words, this would be
a, b = some_right_hand_side_value

I was wondering abt the sequence after that.
say a = 'A' and b = 'B' initially.

If the assignment a = 'B' happens first, then won't the assignment for b
will be 'B' itself as the value referenced by "a" on the RHS will be changed
?

Or is it that all the objects on the RHS are replaced by their values before
the assignment happen ?

i.e, a, b = 'B', 'A'

Just making sure !!!

Rgds,
Praveen.

----- Original Message -----
From: "Daniel Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Praveen Pathiyil" <ppathiyi@cisco.com>
Cc: <tutor@python.org>
Sent: Thursday, May 10, 2001 3:50 PM
Subject: Re: Multiple Assignments...


> On Thu, 10 May 2001, Praveen Pathiyil wrote:
>
> >         Can you tell me how the multiple assignments in python work in
> > case of swapping (may be from interpreter point of view) ? I found the
> > below assignment strange given the conventional way of storing in temp
> > and all.
>
> Sure!  Let me forward this to the tutor@python.org mailing list too, since
> this is an issue that other people might want to know about.
>
>
> > a, b = b, a
>
> Python needs to figure out the value at the right of the assignment.
> Let's call this value the "right hand side"; Python will ignore the left
> hand side of the equation for the moment.
>
> Let's stare more at the right hand side. The expression:
>
>     b, a
>
> is the tuple
>
>    (b, a)
>
> in disguise; with those commas, Python infers that we mean a "tuple".  So
> what's on the right hand side is the tuple that contains the values of 'b'
> and 'a'.  You can imagine that what we have, now, looks something like:
>
>     a, b = some_right_hand_side_value
>
> This is the part that might seem weird, just because when we see the
> equals sign '=', we might think that everything happens simultaneously,
> like some math equation.  However, what we don't see is that there's an
> intermediate step, where it needs to first grab the value of the right
> hand, and then it proceeds with the assignment.
>
>
> On a related note, this temporary evaluation of the right hand side is
> what allows us to write things like:
>
>    a = a + 1
>
> without violating the laws of nature. the roles of variables are different
> depending on which side they straddle the equal '=' sign.  When they're on
> the right we're trying to load the values contained in them.  On the left,
> we're storing into these variables.
>
>
> Let's go back to the tuple assignment question.  Now that we have this
> situation:
>
>     a, b = some_right_hand_side_value
>
> Python can easily assign 'a' to the first value in some right hand side
> value, and 'b' to the second element.
>
>
>