GeekChick GeekChick - 1 year ago 74
Python Question

Swapping values in assignemnt

I'm a newbie taking Udacity's Intro to Computer Science course. We had a fairly simple question on our quiz about swapping values and I don't quite understand it. Here is the question:

Which of the following sequence of statements leaves the value of variable X the same as it was before the statements. Assume that both a and x refer to the integer values before this code.

Why is this true?

a,x = x,a
a,x = x,a

For example if I have:

a,x = 4,5

a = 4 and x = 5

For the second part:

a,x = 5, 4

then a = 5 and x = 4
So x is not equal to what it was before. Can someone explain why this is true?

Answer Source

It's simply swapping, then swapping again.

>>> a = 2
>>> x = 1
>>> a,x = x,a # We swapped them, so a = 1 and x = 2 now
              # During evaluation, this statement will be equivalent to "a,x = 1,2"
>>> a,x = x,a # And now we swap them again, so they're back to their original values
              # During evaluation, this statement will be equivalent to "a,x = 2,1"
>>> a
>>> x

What it seems you're missing is that the values change in the middle. You can't go through at the beginning and replace all occurrences of x and a with 4 and 5 in your example because x and a change in the middle of the operation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download