1

I have two variables, x and y, and I want to swap their values. (For example, if x has value 20 and y has value "princess", then after the swap I want x to have value "princess" and y to have value 20.)

Can you explain why the code x = y y = x doesn't work.

I know how to use the temp variable and x,y but I was confused as to why the above method doesn't work. I have no code except for

x=y
y=x

I just need someone to explain why the method above doesn't work.

Hana K
  • 19
  • 2
  • 2
    Think about what would happen in this code. Once you've done `x=y`, what has happened to the original value of `x`? – Daniel Roseman Apr 29 '19 at 20:43
  • 1
    This is a great question to trace manually on paper. Make a column for `x` and a column for `y`. Put the initial values in each column. Trace through each line of code and update the variable values in each column. See what happens. – Fred Larson Apr 29 '19 at 20:50

3 Answers3

3

In your example, once you assign the value of y to x, you no longer have a reference to x's original value so the next operation doesn't work.

Try:

y,x = x,y

Facts and myths about Python names and values

wwii
  • 23,232
  • 7
  • 37
  • 77
2

I'll explain with an example:

x = 20 
y = 5 

x = y ---> x is now 5 
y = x ---> y is now 5 too 

If you want to swap them, you need to do in python e.g.:

x, y = y, x

See here

Edit: You mentioned that you want to assign the values "princess" - a String and 20 - an integer. In (most) programming languages you define the data type of the variable and you can't assign an integer to variable which was defined as a String and vice versa.

kevinunger
  • 334
  • 5
  • 13
0

Let's say x = 5 and y=10.

After x = y is executed, x = 10 and y = 10.

After y = x is executed, x still = 10 and y still = 10.

So x = y = 10.

To swap two variables, Python has this built in: use x, y = y, x.

Jackson H
  • 171
  • 10