Member-only story

5 ways to swap two numbers in Python

Python Coding
2 min readAug 15, 2024

--

1. Using a Temporary Variable:

a = 5
b = 10
temp = a
a = b
b = temp
print("After swapping: a =", a, ", b =", b)#clcoding.com
After swapping: a = 10 , b = 5

2. Without Using a Temporary Variable :

a = 5
b = 10
a = a + b
b = a - b
a = a - b
print("After swapping: a =", a, ", b =", b)#clcoding.com
After swapping: a = 10 , b = 5

3. Using Tuple Unpacking:

a = 5
b = 10
a, b = b, aprint("After swapping: a =", a, ", b =", b)#clcoding.com
After swapping: a = 10 , b = 5

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet