Swapping Two Variables Using Python

In Python values of two variables can be easily swapped with each other. For example – If there is a variable x = 10 and other one y = 5 then swapping values of x, y variables with each other and making x = 5, y = 10 is super simple in Python Programming Language.

Below is Python Code for Swapping Two Variables

  • Define two variables for example x = 10, y = 5
  • Define a temporary variable temp and makes it equal to x using temp = x statement
  • Now assign value of y to x using x = y statement
  • Assign y value of temporary variable(temp) using y = temp statement

That’s it now value of x have become value of y and vice-versa.

# Swapping two variables in Python Programming Language
x = 10
y = 5

# Let's swap x and y values
temp = x
x = y
y = temp

# Printing out new swapped values of x, y
print("After swapping x is =>", x)
print("After swapping y is =>", y)

Output of Above Code

After swapping x is => 5
After swapping y is => 10

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts