- Trending Categories
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
- Related Articles
- Swap two variables in one line using C#
- Swap two variables in one line in using Java
- Swap two variables in one line in Java
- Swap two variables in one line in C/C+
- Swap two variables in one line in C/C++, Python, PHP and Java
- How to Swap Two Variables using Python?
- How to swap two variables in JavaScript?
- How to swap variables using Destructuring Assignment in JavaScript?
- How to swap two files in Linux command line?
- Previous Permutation With One Swap in Python
- How to swap two String variables without third variable.
- How to swap variables with destructuring in JavaScript?
- How to compare two variables in an if statement using Python?
- Swap two Strings without using temp variable in C#
- Next higher number using atmost one swap operation in C++

Advertisements