5 Ways to Swap Variables in Python:
1. Using a Temporary Variable -
a=2
b=3
temp=a
a=b
b=temp
print(a)
print(b)
Output:-
a=3
b=2
2. Using Arithmetic Operators -
a=2
b=3
a=a+b # a=5, b=3
b=a-b # a=5, b=2
a=a-b # a=3, b=2
print(a)
print(b)
Output:-
a=3
b=2
3. Using Comma -
a=2
b=3
a,b=b,a
print(a)
print(b)
Output:-
a=3
b=2
4. Using XOR(^)
a=2
b=3
a=a^b
b=a^b
a=a^b
print(a)
print(b)
Output:-
a=3
b=2
5. Using Multiplication and Division -
a=2
b=3
a=a*b
b=a/b
a=a/b
print(a,b)
Output:-
a=3, b=2
Comments
Post a Comment
Please do not enter any spam link in the comment box.