-1

If we write a simple program in python as mentioned below, the variables get swapped

num1=5
num2=10
temp = num1
num1 = num2
num2 = temp

print(num1) //10

print(num2) //5

But if we perform the same thing inside a function, the values do not get swapped

def swap(x, y):
   
    temp = x
    x = y
    y = temp

Driver code

x = 2
y = 3
swap(x, y)
print(x)    //2
print(y)    //3

I want to know the concept that in first case it is getting swapped but in second case why it is not getting swapped ?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Anil
  • 33
  • 7
  • You've introduced local variables in the function that just happened to be named the same... If you had `def swap(a, b)`, what would you have expected? And when you set an equality, you're reassigning a reference, not "storing a value" to that variable name – OneCricketeer Feb 01 '21 at 04:41

1 Answers1

0

You can swap x and y like this

x,y=y,x

If you want to wrap it in a function

def swap(x,y):
    return y,x

x,y = swap(x,y)
Mitchell Olislagers
  • 1,758
  • 1
  • 4
  • 10