Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Swap two variables in python without using third variable

swap two variables

Swap two variables

Swapping two variables by using third variable can be done easily by just preserving data before assigning to another variable, but this doesn’t work in this case as third variable not to be used.So we use some arithmetic operations to perform Swap of two variables in python without using third variable

Sample input: a=34 b=12

Sample output: a=12 b=34

To check Swap two variables in Python

Working of Swap two variables in python without using third variable

  • Step 1: Read the input variable “a”
  • Step 2: Read the input variable “b”
  • Step 3: Print the present a and b values
  • Step 4: apply arthematic operations
  • Step 5: print the swapped values of  a and b
    a=a+b=34+12=46
    b=a-b=46-12=34
    a=a-b=46-34=12

Python code for  Swapping two variables without third variable:

Solution 1:

a=int(input(“Enter value : “))
b=int(input(“Enter value : “))

print(“Before swapping a :”,a)
print(“Before swapping b :”,b)
#logic to swap without using third variable 
a=a+b 
b=a-b
a=a-b


print(“After swapping a becomes :”,a)
print(“After swapping b becomes :”,b) 
Enter value : 34
Enter value : 12
Before swapping a : 34
Before swapping b : 12
After swapping a becomes : 12
After swapping b becomes : 34

Spoiler  alert : This code works only for integer data , to swap all datatype below code works efficiently

Working

  • Step 1: Read the input variable “a”
  • Step 2: Read the input variable “b”
  • Step 3: Print the present a and b values
  • Step 4: Swap a and b values  using a,b=b,a 
  • Step 5: Print swapped a and b values

Solution 2:

a=(input(“Enter value : “))
b=(input(“Enter value : “))

print(“Before swapping a :”,a)
print(“Before swapping b :”,b)
#logic to  swap without using third variable 
a,b=b,a


print(“After swapping a becomes :”,a)
print(“After swapping b becomes :”,b) 
Enter value : prepinsta
Enter value : 1234
Before swapping a : prepinsta
Before swapping b : 1234
After swapping a becomes : 1234
After swapping b becomes : prepinsta