Tags
Asked 2 years ago
30 Jul 2021
Views 320
Gwen

Gwen posted

How to swap two variables in Python program ?

i am new to Python coding , dont know how to swap value of two variables in Python Script

a=1
b=3
print("a is {0} b is {1}".format(a,b))
 

How to swap two variables in Python program ?
andy

andy
answered Jul 30 '21 00:00

to swap value of two variables, Without using any third variable, see this code

a='Aron'
b='Byte'
print("a is {0} b is {1}".format(a,b))
a,b=b,a
print("swap done : a is {0} b is {1}".format(a,b))


will print like this

a is Aron b is Byte
swap done: a is Byte b is Aron


here magic of Python is swap value with just a,b =b,a
a,b =b,a is short hand code of a=b and b=a

How to swap three variables values with each other in Python?
hmm , same as above by using short hand code
we simply rotating value to each other in three variables


a='Aron'
b='Byte'
c='Rand'
print("a is {0} b is {1}".format(a,b))
a,b,c=c,a,b
print("swap done: a is {0} b is {1} c is {2}".format(a,b,c))


ouput :

a is Aron b is Byte
swap done: a is Rand b is Aron c is Byte

a,b,c=c,a,b means
a=c
b=a
c=b
so value of "c" is goes to "a" , and value of "a" goes into "b" and value of "b" goes to "c"

you can swap any number variables like
a,b,c,d,e=e,a,b,c,d

eclipse-learner

eclipse-learner
answered Jul 30 '21 00:00

to swap two variables , you need one extra variable to hold value when we swaping value .
Please check belowe code for the swapping two variables in Python :


a=1
b=3
print("a is {0} b is {1}".format(a,b))
c=a;
a=b;
b=c;
print("after swap a is {0} b is {1}".format(a,b))


output will be :

a is 1 b is 3
after swap a is 3 b is 1
Post Answer