- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap two variables in one line in using Python?
We will learn how to swap two variables in one line. Let’s say the following is our input −
a = 10 b = 5
The following is our output after swap −
a = 5 b = 10
Swap two variables in one line using comma operator
Using the comma operator, you can create multiple variables in a single line. The same concept is considered here and the variable values are swapped −
Example
a = 5; b = 10; print("Variable1 = ",a); print("Variable2 = ",b); # Swap two variables in one line using comma operator a, b = b, a print("\nVariable1 (After Swapping) = ",a); print("Variable2 (After Swapping) = ",b);
Output
Variable1 = 5 Variable2 = 10 Variable1 (After Swapping) = 10 Variable2 (After Swapping) = 5
Swap two variables using multiplication and division operator
Swapping variables in Python can be achieved using the operators −
Example
a = 5; b = 10; print("Variable1 = ",a); print("Variable2 = ",b); # Swap two variables a = a * b b = a / b a = a / b print("\nVariable1 (After Swapping) = ",a); print("Variable2 (After Swapping) = ",b);
Output
Variable1 = 5 Variable2 = 10 Variable1 (After Swapping) = 10.0 Variable2 (After Swapping) = 5.0
Swap two variables using XOR
Swapping variables in Python can be achieved using the XOR operator −
Example
a = 5; b = 10; print("Variable1 = ",a); print("Variable2 = ",b); # Swap two variables a = a ^ b b = a ^ b a = a ^ b print("\nVariable1 (After Swapping) = ",a); print("Variable2 (After Swapping) = ",b);
Output
Variable1 = 5 Variable2 = 10 Variable1 (After Swapping) = 10 Variable2 (After Swapping) = 5
Advertisements