Learn the Techniques: How to Reverse a Number in Python Efficiently

By Pavan Vadapalli

Updated on Oct 10, 2025 | 24 min read | 15.79K+ views

Share:

Reversing a number in Python is a common task in programming and algorithm challenges. It involves rearranging the digits of a number so that the last digit becomes the first and the first becomes the last. Python provides multiple ways to achieve this efficiently, from arithmetic operations to loops and built-in functions. Knowing these techniques helps you solve coding problems faster and write cleaner code. 

In this guide, you'll read more about the concept of number reversal, step-by-step methods using arithmetic, string conversion, for and while loops, and functions. We’ll also explore advanced techniques like recursion and list comprehension, compare all methods for efficiency, and show practical applications.  

Shape your future with upGrad’s Data Science Course. Gain hands-on expertise in AI, Machine Learning, and Data Analytics to become a next-generation tech leader. Enroll today and accelerate your career growth.

Methods to Reverse a Number in Python

Reversing a number in Python can be done in several ways. Each method has its own advantages. You can choose based on your coding style, performance needs, or the problem you are solving. Below, we’ll explore the most common techniques with clear examples. 

1. Using Arithmetic Operations 

The arithmetic method uses modulus and floor division to extract and reverse digits. This approach works without converting the number into a string. 

Steps

  • Take the last digit using % 10. 
  • Add it to a new reversed number multiplied by 10. 
  • Remove the last digit from the original number using // 10. 
  • Repeat until the original number is 0. 

Example Code

num = 12345 
reversed_num = 0 
 
while num > 0: 
    digit = num % 10 
    reversed_num = reversed_num * 10 + digit 
    num = num // 10 
 
print("Reversed Number:", reversed_num) 

Output

Original Number 

Reversed Number 

12345  54321 

Pros: No type conversion, efficient. 

Cons: Slightly more steps than string methods. 

Also Read: What are Assignment Operators in Python? 

2. Using String Conversion 

Python makes it simple by converting numbers into strings. You can reverse the string and convert it back to an integer. 

Example Code

num = 12345 
reversed_num = int(str(num)[::-1]) 
print("Reversed Number:", reversed_num) 
  

Output: 54321 

Pros: Very concise, easy for beginners. 

Cons: Involves type conversion.  

3. Using For Loop 

You can use a for loop to iterate over the digits of a number (after converting it to a string) and build the reversed number manually. 

Example Code

num = 12345 
reversed_num = 0 
 
for digit in str(num): 
    reversed_num = reversed_num * 10 + int(digit) 
 
print("Reversed Number:", reversed_num) 

Pros: Clear logic, beginner-friendly. 

Cons: Slightly longer code than slicing method. 

Also Read: Nested For Loop in Python: How It Works with Examples 

4. Using While Loop 

A while loop is similar to the arithmetic method but emphasizes iteration until a condition is met. 

Example Code

num = 12345 
reversed_num = 0 
 
while num != 0: 
    reversed_num = reversed_num * 10 + num % 10 
    num = num // 10 
 
print("Reversed Number:", reversed_num) 
  

This is ideal for dynamic input, where the number changes during runtime. 

Also Read: Python While Loop Statements: Explained With Examples 

5. Using Functions 

You can also create a reusable function for reversing numbers. 

Example Code

def reverse_number(num): 
    reversed_num = 0 
    while num > 0: 
        reversed_num = reversed_num * 10 + num % 10 
        num = num // 10 
    return reversed_num 
 
print(reverse_number(12345)) 

Pros: Makes your code modular and easy to reuse. 

Also Read: Most Important Python Functions [With Examples] | Types of Functions 

Comparison Table of Methods 

Method 

Ease of Use 

Speed 

Memory 

Best For 

Arithmetic Operations  Medium  Fast  Low  Large numbers, no conversion 
String Conversion  Easy  Medium  Medium  Beginners, quick coding 
For Loop  Easy  Medium  Medium  Step-by-step learning 
While Loop  Medium  Fast  Low  Dynamic or unknown numbers 
Functions  Medium  Fast  Low  Reusable code, multiple uses 

These methods cover all common ways to reverse a number in Python. Beginners can start with string conversion for simplicity, while advanced programmers might prefer arithmetic operations for performance. Using functions helps make your code cleaner and reusable.

Advanced Techniques to Reverse a Number in Python 

Once you are comfortable with the basic methods, Python also allows advanced techniques to reverse a number in Python efficiently. These approaches are useful when you want concise code, reusable functions, or are handling complex scenarios. 

1. Using Recursion 

Recursion lets a function call itself until a base condition is met. You can use recursion to reverse a number in Python by processing one digit at a time. 

Steps

  • Extract the last digit using % 10. 
  • Append it to the reversed number returned by the recursive call. 
  • Stop recursion when the number becomes 0. 

Example Code

def reverse_number(num): 
    if num == 0: 
        return 0 
    else: 
        digits = len(str(num)) - 1 
        return (num % 10) * (10 ** digits) + reverse_number(num // 10) 
 
print(reverse_number(12345)) 
  

Output: 54321 

Pros: Elegant and demonstrates programming concepts. 

Cons: Slightly slower for very large numbers due to multiple function calls. 

Also Read: Top 50 Python Project Ideas with Source Code in 2025 

2. Using List Comprehension 

List comprehension can also be used to write a program to reverse a number in Python in a concise way. Convert the number to a string, iterate in reverse, and join the digits back. 

Example Code

num = 12345 
reversed_num = int(''.join([digit for digit in str(num)][::-1])) 
print(reversed_num) 
  

Output: 54321 

Pros: Short and clean code. 

Cons: Slightly less intuitive for beginners. 

3. Handling Large Numbers Efficiently 

For large numbers, performance varies depending on the method. Arithmetic operations are usually faster and use less memory than string conversion, recursion, or list comprehension. 

Performance Table

Method 

Speed 

Memory Usage 

Best Use Case 

Arithmetic Operations  Fast  Low  Large numbers, high efficiency 
String Conversion  Medium  Medium  Moderate-sized numbers 
Recursion  Slow  Medium-High  Learning recursion 
List Comprehension  Medium  Medium  Concise code, small numbers 

 4. Combining Methods for Flexibility 

You can combine methods depending on the scenario: 

  • Use arithmetic operations for high-performance tasks. 
  • Use string conversion or list comprehension for shorter code. 
  • Use functions and recursion for reusable code and concept demonstration. 

Example: Recursive Function 

def reverse(num, rev=0): 
    if num == 0: 
        return rev 
    return reverse(num // 10, rev * 10 + num % 10) 
 
print(reverse(12345)) 

Output: 54321 

These advanced techniques allow you to reverse a number in Python efficiently while keeping your code readable and reusable. Beginners can start with recursion or list comprehension, while arithmetic operations are ideal for performance-critical tasks. 

Comparing All Methods 

After exploring the various ways to reverse a number in Python, it is helpful to compare them side by side. This allows you to choose the best method based on ease, performance, and readability. Each approach has its strengths and trade-offs. 

Key Comparison Points 

When deciding how to write a program to reverse a number in Python, consider: 

  • Ease of Use: How simple is it for beginners? 
  • Performance: How fast does it execute, especially for large numbers? 
  • Memory Usage: Does it use extra space for conversions or recursion? 
  • Readability: How easy is it to understand and maintain? 

Also Read: Why Learn Python – Top 10 Reasons to Learn Python in 2024 

Comparison Table 

Method 

Ease of Use 

Speed 

Memory Usage 

Best For 

Arithmetic Operations  Medium  Fast  Low  Large numbers, performance-critical 
String Conversion  Easy  Medium  Medium  Beginners, small to medium numbers 
For Loop  Easy  Medium  Medium  Step-by-step learning, clarity 
While Loop  Medium  Fast  Low  Dynamic input, general use 
Recursion  Medium  Slow  Medium-High  Learning recursion, concept practice 
List Comprehension  Medium  Medium  Medium  Concise code, small numbers 
Function-based Approach  Medium  Fast  Low  Reusable code, multiple calls 

Choosing the Right Method 

  • Beginners: Start with string conversion or for loops. They are easy to understand and quick to implement. 
  • Intermediate coders: Use while loops or function-based arithmetic methods for better control and performance. 
  • Advanced programmers: Try recursion or list comprehension for concise code or concept practice. 

Tip: For coding interviews or competitive programming, arithmetic operations are preferred due to speed and low memory usage. 

This comparison ensures that beginners and advanced users can pick the right approach for their needs. 

Also Read: Python Challenges for Beginners 

Data Science Courses to upskill

Explore Data Science Courses for Career Progression

background

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

Understanding the Concept of Number Reversal 

Before you start coding, it is important to understand what it means to reverse a number in Python. Number reversal is simply rearranging the digits of a number so that the last digit becomes the first, the second last becomes the second, and so on. For example, 12345 becomes 54321. 

Reversing numbers is a fundamental concept in programming. It helps you practice logic, loops, and arithmetic operations. You will encounter it often in coding challenges, algorithm problems, and Python exercises. 

Key Points to Remember 

When learning how to reverse a number in Python, keep these points in mind: 

  • A number like 12345 reversed becomes 54321
  • Leading zeros in the reversed number are usually removed (e.g., 120 → 21). 
  • Negative numbers retain their sign (e.g., -123 → -321). 
  • Python allows multiple ways to achieve this: arithmetic, string conversion, loops, recursion, and more. 

Also Read: Step-by-Step Guide to Learning Python for Data Science  

Original vs Reversed Number Table 

Original Number 

Reversed Number 

12345  54321 
120  21 
-987  -789 
1001  1001 

This table helps beginners see how numbers change when reversed. 

String vs Number Reversal 

It’s important to know the difference between reversing a number as an integer and reversing it as a string

  • Integer reversal uses arithmetic operations to manipulate digits directly. 
  • String reversal converts the number into a string, reverses the characters, then converts it back to an integer. 

Both approaches achieve the same result, but the methods are different in performance and readability. 

Common Challenges 

  • Negative numbers: Ensure the minus sign stays at the beginning. 
  • Leading zeros: Numbers like 1000 should reverse to 1, not 0001. 
  • Input validation: Ensure the value is a number before attempting to reverse it. 

Also Read: Top 70 Python Interview Questions & Answers: Ultimate Guide 2025 

Summary

  • Reverse digits without changing their values 
  • Handle negatives correctly 
  • Remove unnecessary leading zeros 
  • Choose the method based on readability and efficiency 

Understanding these concepts lays a solid foundation. Once you grasp them, you can easily write a program to reverse a number in Python using any method. It also makes learning advanced techniques like loops, recursion, and functions more intuitive. 

Become an Expert at Python with upGrad! 

Reversing a number in Python requires choosing the right algorithm, as methods like recursion, loops, and slicing impact performance and efficiency. Experiment with different approaches like loops, recursion, and string manipulation to understand their trade-offs in efficiency.  

Struggling with choosing the proper method for complex problems? Consider upGrad’s additional courses to tackle challenges and gain expertise in algorithms and Python programming.  

Curious which courses can help you strengthen your knowledge in Python? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center.

Test Your Knowledge on Reversing Numbers in Python!

Assess your understanding of different methods to reverse a number in Python, including key concepts and practical use cases by answering the following multiple-choice questions. Challenge yourself and see how well you know Python's number reversal techniques! 

Test your knowledge now!

Q1. What is the simplest way to reverse a number in Python?
A) Using a for loop
B) Using string slicing
C) Using recursion
D) Using the reversed() method

Q2. Which Python method can you use to reverse a string?
A) reverse()
B) pop()
C) join()
D) split()

Q3. How does recursion help in reversing a number?
A) By repeatedly extracting the last digit and appending it
B) By reversing the number in-place
C) By using a loop to iterate through digits
D) By converting the number to a string

Q4. What happens if you reverse a number using the reverse() method in Python?
A) It returns a reversed list
B) It modifies the original number
C) It reverses the digits in-place
D) It raises an error

Q5. Which of the following is the correct syntax to reverse a number using string slicing?
A) str(num)[::-1]
B) num.reverse()
C) reverse(num)
D) num[::-1]

Q6. In which scenario would recursion be a better method for reversing a number in Python compared to other methods?
A) When working with very large numbers
B) When handling very simple number reversal tasks
C) When you want to test recursion techniques
D) When working with strings only

Q7. How do you reverse a number using the reversed() function?
A) reversed(str(num))
B) reversed(num)
C) num[::-1]
D) reverse(num)

Q8. Can you reverse a number using a list in Python?
A) No, lists do not support reversing
B) Yes, by converting the number to a list and using reverse()
C) Yes, by using a dictionary
D) No, you need a different data structure

Q9. What is the advantage of using a while loop to reverse a number in Python?
A) It’s faster than other methods
B) It avoids converting the number to a string
C) It’s simpler than using recursion
D) It automatically detects the length of the number

Q10. How can you reverse a number using the pop() method in Python?
A) By adding the digits to the list and popping them one by one
B) By using pop() in a while loop
C) By converting the number to a string and popping each character
D) pop() cannot be used for number reversal

Also read: Top 36+ Python Projects for Beginners and Students to Explore in 2025

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!

Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!

Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!

Reference: 
https://content.techgig.com/technology/python-dominates-2025-programming-landscape-with-unprecedented-popularity/articleshow/121134781.cms

Frequently Asked Questions (FAQs)

1. How does recursion work for reversing a number in Python?

Recursion reverses a number by repeatedly extracting the last digit and appending it to the result. Each recursive call reduces the number, extracting one digit at a time. The base case ensures the process stops once the number becomes 0. This method is memory-efficient, as it avoids constructing intermediate sequences.

2. What’s the time complexity of reversing a number using string slicing in Python?

String slicing in Python has a time complexity of O(n), where n is the number of digits in the number. The operation iterates through the number's digits, processing each one once. This makes it efficient for reversing smaller numbers or when simplicity is preferred. However, larger numbers may require more memory for string conversion.

3. When should you use a while loop to reverse a number in Python?

A while loop is ideal when you need low-level control over digit extraction and reversal. This approach avoids string manipulation, keeping the number in its integer form. It works efficiently for problems requiring manual digit manipulation, such as algorithmic challenges. The method is also space-efficient, only requiring a few integer variables.

4. How does the reversed() method differ from string slicing in Python?

The reversed() method returns an iterator, which generates the digits in reverse order without creating a new list. In contrast, string slicing creates a reversed copy of the entire string in memory. While slicing offers simplicity, reversed() can be more efficient for iterating over large sequences. The choice depends on memory constraints and use cases.

5. Can reversing a number using a stack improve performance in Python?

Using a stack introduces O(n) space complexity, as each digit is pushed into the stack. The stack follows a Last-In-First-Out (LIFO) order, making it a natural fit for reversing sequences. While it’s not the most memory-efficient method, it provides a clear and structured approach to reversing numbers. It's useful for understanding stack operations in algorithms.

6. Why is string manipulation preferred for reversing a number in Python?

String manipulation, such as slicing or joining, offers simplicity and clarity when reversing a number. It avoids complex logic and makes the code highly readable. This method is often more intuitive for beginners and efficient for small to medium-sized numbers. However, for large numbers, string manipulation can increase memory overhead.

7. How does a list-based approach to reverse a number compare to other methods?

The list-based approach splits the number into individual digits, stores them in a list, and reverses the list. It requires O(n) space for storing the digits and introduces some overhead. Once reversed, the list is joined back into a string and converted back to an integer. This method is flexible but can be more memory-intensive than alternatives.

8. What is the advantage of using a for loop to reverse a number in Python?

A for loop provides a clean way to iterate through the string representation of the number. Each digit is processed and added to the reversed number in a controlled manner. The method avoids recursion and the complexity of manipulating the number directly. It's efficient for situations where simple string manipulation is required.

9. What are the key differences between using recursion and iteration for reversing a number?

Recursion uses repeated function calls to break the problem into smaller subproblems, handling one digit per call. Iteration, on the other hand, uses a loop to process each digit directly within the main function. Recursion offers a cleaner and more elegant solution, while iteration is often faster and more straightforward. Iteration avoids the overhead of multiple function calls.

10. Can reversing a number in Python lead to integer overflow?

Reversing a number in Python typically does not cause overflow, as Python supports arbitrary-precision integers. The reversed number may exceed typical integer ranges in other languages, but Python handles it efficiently. However, when working with external systems, you may encounter integer limits in databases or APIs. Always validate constraints when dealing with large numbers in integrated systems.

11. What’s the best method to reverse a number in Python for competitive programming?

For competitive programming, a while loop or recursion is often preferred for its direct approach to digit manipulation. These methods avoid the overhead of string conversion, which can slow down performance. Recursion is cleaner, but iteration with a while loop offers better performance in space-constrained environments. Both methods allow for fast, in-place number reversal.

Pavan Vadapalli

907 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India...

Speak with Data Science Expert

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree

17 Months

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in DS & AI

360° Career Support

Executive PG Program

12 Months