PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Swap Two Numbers

Python Swap Two Numbers

Updated on: March 27, 2025 | 1 Comment

Swapping two numbers is a common task in programming, and Python offers several ways to achieve this. This tutorial covers all the major methods, along with detailed descriptions and examples for each approach.

Each of these methods achieves the same result, showcasing the versatility of Python and programming techniques in general. Let’s see the example of each method individually.

1. Swap two numbers using tuple unpacking

This is the most Pythonic and concise method to swap two numbers. Here’s how you do it:

Code Example

# Initializing numbers
a = 50
b = 100

# Swapping using tuple unpacking
a, b = b, a

print("After swapping:")
print("a =", a)
print("b =", b)Code language: Python (python)

Output:

After swapping:
a = 100
b = 50

Explanation

  • a and b are initially set to 50 and 100, respectively.
  • Python allows multiple assignments in a single line using tuples. This feature simplifies swapping by eliminating the need for intermediate variables or complex operations.
  • The right-hand side (b, a) creates a tuple that temporarily holds the values, ensuring the original values remain intact until reassignment.
  • The left-hand side unpacks the tuple into a and b, completing the swap efficiently and in a single step
  • After the swap, a will be 100 and b will be 50.

2. Swap two numbers using Temporary Variable

This is one of the most straightforward methods. Here, a temporary variable is used to hold one of the values during the swap.

Code Example

# Initializing numbers
a = 50
b = 100

# Print original values
print("Original values:")
print("a =", a)
print("b =", b)

# Using a temporary variable
temp = a
a = b
b = temp

print("After swapping:")
print("a =", a)
print("b =", b)

<strong>Output</strong>:Code language: Python (python)
Original values:
a = 50
b = 100

After swapping:
a = 100
b = 50

Explanation

  1. First, the value of a is saved in the variable temp. This ensures the original value of a is not lost when its value is replaced in the next step.
  2. The value of b is then assigned to a. At this point, a takes on the value of b, completing half of the swap.
  3. Finally, the value stored in temp (which holds the original value of a) is assigned to b. Now, b has the original value of a, completing the swap.
  4. This approach is simple to understand and demonstrates the basic concept of using extra memory to facilitate swapping. the value of a in temp.
  5. Assign the value of b to a.
  6. Assign the value of temp (which holds the original value of a) to b.

3. Swap two numbers without using a temporary variable

This method eliminates the need for an extra variable by using arithmetic operations. Using arithmetic operations, addition and subtraction, we can swap two numbers in Python.

Code Example

Example 1: Using Addition and Subtraction

a = 50
b = 100

print("Before swapping:")
print("a =", a, "b =", b)

# Swapping without a temporary variable
a = a + b  # a now holds the sum of a and b
b = a - b  # b now holds the original value of a
a = a - b  # a now holds the original value of b

print("After swapping:")
print("a =", a)
print("b =", b)

<strong>Output</strong>:Code language: Python (python)
Before swapping:
a = 50 b = 100

After swapping:
a = 100
b = 50

Example 2: Using Multiplication and Division

# Initializing numbers

a = 50
b = 100

print("Before swapping:")
print("a =", a, "b =", b)

# Swapping without a temporary variable
a = a * b
b = a // b
a = a // b

print("After swapping:")
print("a =", a)
print("b =", b)Code language: Python (python)

Output:

Before swapping:
a = 50 b = 100

After swapping:
a = 100
b = 50

Explanation

  1. Using addition/subtraction or multiplication/division allows the values to be interchanged without needing extra storage. These arithmetic operations effectively encode both values into a single variable temporarily, enabling the swap.
  2. Note that the multiplication/division approach is not suitable for cases where a or b is zero, as division by zero is undefined and will raise an error in Python.

Note: This method works well for integers but might be prone to rounding errors with floating-point numbers. So, avoid swapping floating-point numbers using this method.

4. Swap two numbers using XOR swap

This method uses the XOR bitwise operator to swap two numbers without using extra memory. Here’s how it works in Python:

Code Example

# Initializing numbers
a = 50
b = 100

print("Before swapping:")
print("a =", a, "b =", b)

# Swapping using XOR
a = a ^ b
b = a ^ b
a = a ^ b

print("After swapping:")
print("a =", a)
print("b =", b)Code language: Python (python)

Output:

Before swapping:
a = 50 b = 100

After swapping:
a = 100
b = 50

Explanation

The XOR operation toggles bits and is used here to store and retrieve values. It works by applying the XOR operation, which ensures that bits differing between the two numbers are toggled while keeping identical bits unchanged.

  • a = a ^ b combines the bits of a and b.
  • b = a ^ b effectively reverses the bits where b originally contributed, leaving a’s original bits in b.
  • a = a ^ b then reverses the bits where a originally contributed, now stored in b, leaving b‘s original bits in a.

It works efficiently and avoids the use of additional variables, making it memory-efficient. This approach is particularly useful in low-level programming and embedded systems where memory is a constraint.

ed using their bit-level representations without needing extra storage for a temporary variable.

5. Swapping in a Function Using Multiple Assignment

You can also encapsulate the swapping logic in a function. Use Python function by leveraging multiple assignments. Here’s a simple example of how you can define such a function:

Code Example

def swap_numbers(a, b):
    print("Before swapping:")
    print("a =", a, "b =", b)
    return b, a

# Initializing numbers
a = 50
b = 100

# Swapping using a function
a, b = swap_numbers(a, b)

print("After swapping:")
print("a =", a)
print("b =", b)Code language: Python (python)

Output:

Before swapping:
a = 50 b = 100

After swapping:
a = 100
b = 50

Explanation

  1. The function swap_numbers returns the swapped values as a tuple. This ensures that the swap logic is reusable and modular, making the code cleaner and more maintainable.
  2. The tuple is unpacked into a and b, allowing the values to be reassigned efficiently in a single operation.
  3. Encapsulating the swap logic in a function is particularly useful in scenarios where the swapping operation needs to be performed multiple times or in different parts of the program.

In this function, swap_numbers takes two arguments, a and b, and returns them in reversed order. When you call this function and assign its output to x and y, Python automatically unpacks the returned tuple into the variables, effectively swapping their values.

6. Swap two numbers Using list indexing

This section highlights the use of lists as an alternative method to swap two numbers. By leveraging list indexing, you can swap the values of two elements directly. The approach is concise and similar to tuple unpacking, providing a Pythonic way to achieve the swap while retaining simplicity.

The flexibility of lists in Python allows for easy manipulation of elements, making this method particularly useful when working with multiple values stored in a list.

Code Example

# Initializing numbers in list
numbers = [50, 100]
print("Before swapping:")
print("a =", numbers[0], "b =", numbers[1])

# Swapping using list indexing
numbers[0], numbers[1] = numbers[1], numbers[0]

print("After swapping:")
print("a =", numbers[0])
print("b =", numbers[1])Code language: Python (python)

Output:

Before swapping:
a = 50 b = 100

After swapping:
a = 100
b = 50

Conclusion

In this tutorial, we covered multiple ways to swap two numbers in Python:

  1. Using a temporary variable
  2. Without a temporary variable (arithmetic operations)
  3. Using tuple unpacking
  4. Using XOR bitwise operator
  5. Swapping in a function
  6. Using collections like lists

Each method has its own advantages. For simplicity and readability, tuple unpacking is the most preferred in Python. Choose the method that best fits your use case and coding style.

Advantages of Each Method

  • Using a Temporary Variable:
    • Advantage: Simple and intuitive, easy to understand for beginners.
    • Scenario: Best for learning or when clarity is more important than optimization.
  • Without a Temporary Variable (Arithmetic):
    • Advantage: Avoids extra memory usage.
    • Scenario: Suitable for environments where memory is a constraint, but ensure values are not zero.
  • Using Tuple Unpacking:
    • Advantage: Concise, Pythonic, and avoids intermediate variables.
    • Scenario: Ideal for Python-specific code where readability and simplicity are prioritized.
  • Using XOR Bitwise Operator:
    • Advantage: Memory-efficient and avoids intermediate variables.
    • Scenario: Useful in low-level programming or embedded systems.
  • Swapping in a Function:
    • Advantage: Modular and reusable code.
    • Scenario: Best for scenarios where swapping is needed frequently or in multiple places.
  • Using Collections (Lists):
    • Advantage: Convenient for handling multiple values in a single container.
    • Scenario: Ideal when numbers are part of a larger data structure.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Manikanta T S says

    May 6, 2025 at 3:34 pm

    It is a really one of the good knowledge library it helps to begineer to advance level programmer i really so happy in this platform.

    Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com