• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Python Program to Swap Two Variables without using Third Variable

Aniruddha Chaudhari/31188/6
CodePython

In this Python programming, we will see how to swap two values without temporary variable and with temporary variables.

Suppose x and y are the two variables. We want to swap the values of these two variables.

How to Write a Python Program to Swap Two Variables?

Here is the program you can use to swap two values using the third variable.

x = 5
y = 10

print "The value of x before swapping:", x
print "The value of y before swapping:", y

# create a temporary variable 'temp'
# swap two values from two different variables

temp = x
x = y
y = temp

print "The value of x after swapping:", x
print "The value of y after swapping:", y

Here we save the value of x in a temp variable. Overwrite value of x with the value of y. Replace the value of y by temp variable.

But Python makes the thing simple. I mean very simple.

Write a Python Program to Swap Two Variables without using Third Variable:

Here is a simple line of code that works for you.

x, y = y, x

You can check out the complete program for swapping two values without using a temporary variable.

x = 5
y = 10

print "The value of x before swapping:", x
print "The value of y before swapping:", y

# No need of temporary variable
# swap the values

x, y = y, x

print "The value of x after swapping:", x
print "The value of y after swapping:", y

Note: As Python uses dynamic data type. This program will work to swap any types of data values such as string, int, float. In the above program, I am using two numeric data type variables for swapping.

Python program to swap two variables without using third variable is most efficient as it does not use any temporary variable. Always prefer to write efficient code which takes less memory in every project.

If you have any other Python trick to swap two variables without using third variable, write in the comment section below.

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Rajesh
    June 6, 2018 at 11:52 pm

    Python is really interesting, nice and super.

    • Reply
      Aniruddha Chaudhari
      July 1, 2018 at 11:41 am

      Absolutely!

      Pythos is Gem 🙂

  • Reply
    Chris
    July 1, 2018 at 10:59 am

    The statement ‘x, y = y, x’ does not mean that an intermediate hidden variable is not used.

    Actually, you can swap two variables without extra register by the binary operation ‘xor’:

    x=x^y
    y=x^y
    x=x^y
    • Reply
      Aniruddha Chaudhari
      July 1, 2018 at 11:45 am

      Yeah, we can do that as well.

      There are also some more other techniques to swap two numbers without a third variable.

      We can also use addition-subtraction, multiplication-division operations as well to swap two numbers.

  • Reply
    BADRI VARUN
    March 13, 2021 at 7:36 pm

    Good Evening sir🙂, How are You sir?

    I have one doubt sir ,please clear my doubt sir

    1)>>> a=5
    >>> b=10
    >>> print(‘The value of before swapping:’,a,b); temp=a;a=b;b=temp;print(‘The value of after swapping:’,a,b);
    The value of before swapping: 5 10
    The value of after swapping: 10 5

    here above program i have print output statement at last two line of above program, but my doubt is, if write above program like this as i shown below
    >>> a=5
    >>> b=10
    >>> print(‘The value of before swapping:’,a,b) ”’here its print output of this statement next line i.e, okay but i dont want print output of this statement here , so i need to print this statement at last line of the program code
    The value of before swapping: 5 10
    temp=a
    a=b
    b=temp
    print(‘The value of after swapping:’,a,b) #here its okay this statement print next line only

    The value of after swapping: 10 5
    NOTE:
    My conclusion is that i want to print first printed statement at last line of the program code, So there is any syntax or trick is available for my doubt or my doubt is a wrong statement !!!

    • Reply
      Aniruddha Chaudhari
      March 17, 2021 at 10:43 pm

      Hi Badri,

      I’m doing good. Hope you are doing good as well.

      If you want to print the original values of the two numbers, you have to print them before swapping. So you can not just move the first print statement to the last.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard