Learn the Techniques: How to Reverse a Number in Python Efficiently
Updated on Oct 10, 2025 | 24 min read | 15.79K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Oct 10, 2025 | 24 min read | 15.79K+ views
Share:
Table of Contents
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.
Popular Data Science Programs
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.
The arithmetic method uses modulus and floor division to extract and reverse digits. This approach works without converting the number into a string.
Steps:
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?
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.
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
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
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
| 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.
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.
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:
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
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.
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 | 
You can combine methods depending on the scenario:
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.
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:
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 | 
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
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.
When learning how to reverse a number in Python, keep these points in mind:
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.
It’s important to know the difference between reversing a number as an integer and reversing it as a string:
Both approaches achieve the same result, but the methods are different in performance and readability.
Also Read: Top 70 Python Interview Questions & Answers: Ultimate Guide 2025
Summary:
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
By submitting, I accept the T&C and 
Privacy Policy
Start Your Career in Data Science Today
Top Resources