How to Reverse a Number in Python?
Updated on May 22, 2025 | 21 min read | 15.05K+ views
Share:
For working professionals
For fresh graduates
More
Updated on May 22, 2025 | 21 min read | 15.05K+ views
Share:
Table of Contents
Did you know? After extensive discussions on the Python forum, the community has reached an agreement on the final shape of PEP 758, which proposes to drop the mandatory parentheses around multiple exception types being intercepted. |
This proposal has been accepted by the Steering Council and is expected to be delivered with Python 3.14 later this year.
The simplest way to reverse a number in Python is by converting it to a string and using slicing to flip it. Reversing a number might seem tricky, but Python provides several straightforward methods to achieve this.
In this tutorial, you’ll learn how to reverse a number in Python using different approaches, and when to use them.
Improve your machine learning skills with upGrad’s online AI and ML courses. Specialize in cybersecurity, full-stack development, game development, and much more. Take the next step in your learning journey!
Reversing a number using a while loop in Python is a common technique that allows for more control over the process compared to simple string manipulation. This method is particularly useful when you're looking to avoid type conversion or when you're working with situations where you need to reverse the digits manually, like in algorithm challenges or in scenarios where space and time complexity matter.
Reversing a number in Python goes beyond simply applying a method. You need to understand how each approach fits into different coding scenarios. Here are three programs that can help you:
For example, if you're writing a function for low-level computations or for situations where working with digits directly is required (e.g., in competitive programming), the while loop method gives you the flexibility to manipulate the number without converting it into a string.
Here’s how we can reverse a number like 12345 using a while loop:
# initialize the number and set up the result variable
number = 12345
reversed_number = 0
#loop through each digit until the number becomes 0
while number > 0:
# Extract the last digit
digit = number % 10 # this gives us the last digit of the number
reversed_number = reversed_number * 10 + digit # shift the current reversed number by one place and add the digit
#remove the last digit from the original number
number = number // 10 # This reduces the number by removing the last digit
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 54321
Explanation:
1. Initialize the number and the result variable:
We start by setting the number we want to reverse, 12345, and initialize reversed_number to 0. This variable will store the reversed version as we process each digit.
2. Looping through the digits:
The while loop continues as long as the number is greater than 0. Inside the loop, we extract the last digit of the number using the modulus operator %. For example, 12345 % 10 gives us the last digit, 5.
3. Building the reversed number:
Once we have the last digit, we update reversed_number. To do this, we first multiply reversed_number by 10 (to shift its digits one place to the left) and then add the current digit to it. This ensures the new digit is added to the right of the previously reversed number. For example, after the first iteration, reversed_number becomes 5.
4. Removing the last digit:
After extracting the last digit, we reduce the original number by dividing it by 10 (using integer division //). This removes the last digit, so in the first iteration, the number becomes 1234, then 123, and so on until it becomes 0.
5. Printing the reversed number:
Finally, once the loop ends (when the number becomes 0), we print the reversed number, which in this case will be 54321.
Key Takeaways:
The concept of reverse a number in Python for loop involves first converting the number into a string and then iterating over each digit in reverse order.This method exists because it's simple and leverages Python’s ability to handle strings efficiently. It’s commonly used in scenarios where you need to reverse numbers as part of string manipulations, like text processing or certain algorithmic tasks. like text processing or certain algorithmic tasks.
Let’s reverse the number 6789 using a for loop:
# initialize the number
number = 6789
# convert the number to a string for easy iteration
str_number = str(number) # convert the number to a string
#initialize the reversed number variable
reversed_number = 0
#loop through each digit in reverse order
for digit in str_number:
#update the reversed number
reversed_number = reversed_number * 10 + int(digit) # multiply by 10 to shift and add the digit
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 9876
Explanation:
1. Initialize the number:
We start with the number 6789 and initialize it as a number.
2. Convert the number to a string:
To easily iterate through each digit of the number, we convert it into a string using str(). This makes it easier to loop through each individual digit. After conversion, str_number becomes '6789'.
3. Initialize the reversed number:
We initialize a variable reversed_number to 0. This will hold the reversed number as we process each digit.
4. Loop through each digit:
We use a for loop to iterate through each character (digit) in str_number. Since str_number is a string, each iteration gives us a digit as a string, which we then convert back to an integer using int().
5. Update the reversed number:
In each iteration of the loop, we multiply the current value of reversed_number by 10 (to shift the digits to the left) and add the current digit. This effectively builds the reversed number from right to left.
6. Printing the reversed number:
After the loop finishes, we print the reversed_number, which now holds the reversed value of the original number.
Key Takeaways:
Also Read: Python Program to Convert List to String
This method of reversing numbers using a for loop is useful when you prefer working with strings or need to apply additional string manipulation.
Reverse a Number in Python Using Recursion
Recursion can be used to reverse a number in Python by repeatedly extracting the last digit and appending it to the result. The function calls itself with the remaining digits until the number becomes 0, at which point the recursion stops, and the reversed number is returned.
This method exists because recursion provides a clean, elegant solution for problems that can be broken down into smaller, repetitive tasks. It’s often used in algorithmic challenges or when you want to practice recursive thinking.
Let’s reverse the number 1234 using a recursive function.
# define the recursive function
def reverse_number(n, reversed_num=0):
#base case: When n becomes 0, return the reversed number
if n == 0:
return reversed_num
# extract the last digit and build the reversed number
digit = n % 10 # get the last digit
reversed_num = reversed_num * 10 + digit # add it to the reversed number
# recur with the remaining number
return reverse_number(n // 10, reversed_num)
# call the function with the original number
number = 1234
reversed_number = reverse_number(number)
print("Reversed number:", reversed_number)
Output:
Reversed number: 4321
Explanation:
1. Define the recursive function:
We define a function reverse_number that takes two parameters: n (the number to reverse) and reversed_num (which will hold the reversed number). Initially, reversed_num is set to 0.
2. Base case:
The base case is when n becomes 0. At this point, we return the reversed_num, which holds the reversed number.
3. Extract the last digit:
We extract the last digit of n using the modulus operator (% 10). This gives us the rightmost digit of the number.
4. Build the reversed number:
We update reversed_num by multiplying it by 10 (to shift the digits) and adding the extracted digit.
5. Recursive call:
We call the reverse_number function recursively, passing the integer division of n by 10 (n // 10) to remove the last digit and continue the process until the base case is met.
6. Calling the function:
We call the reverse_number function with 1234, and it returns 4321 after the recursion completes.
Key Takeaways:
Also Read: Recursive Feature Elimination: What It Is and Why It Matters?
How to Reverse a Number in Python Using String Slicing
Reversing a number using string slicing in Python is a simple and intuitive approach. In this approach, you convert the number to a string and use slicing to reverse the string.
This method exists because slicing is a powerful feature in Python that allows for easy manipulation of strings. It’s commonly used by beginners or anyone looking for a quick, straightforward solution to reverse a number without needing extra logic or loops.
#convert the number to a string
number = 98765
str_number = str(number)
# use string slicing to reverse the string
reversed_str = str_number[::-1]
# convert the reversed string back to an integer
reversed_number = int(reversed_str)
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 56789
Explanation:
1. Convert the number to a string:
First, we convert the number 98765 to a string using str(number). This allows us to manipulate the digits easily as characters.
2. String slicing to reverse:
The key here is using string slicing. The syntax [::-1] is a shorthand to reverse the string. It means:
So, str_number[::-1] reverses the string '98765' to '56789'.
3. Convert the reversed string back to an integer:
After reversing the string, we convert it back to an integer using int(). This gives us the reversed number in its integer form.
4. Print the reversed number:
Finally, we print the reversed number, which is 56789.
Key Takeaways:
Also Read: Different Ways of String formatting in Python: Top 3 Methods
How to Reverse a Number in Python Using the reversed() Method
Reversing a number using the reversed() method is another straightforward approach in Python. Unlike other methods, reversed() works with any iterable, including strings and lists. This method exists because it provides a built-in way to reverse the order of elements in an iterable, making it versatile and efficient for various tasks.
To reverse a number using this method, we’ll first convert it to a string, reverse the string, and then convert it back to an integer.
# convert the number to a string
number = 8901
str_number = str(number)
# reverse the string using the reversed() method
reversed_str = ''.join(reversed(str_number))
# convert the reversed string back to an integer
reversed_number = int(reversed_str)
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 1098
Explanation:
1. Convert the number to a string:
The first step is to convert the number 8901 into a string using str(number). This step is necessary because the reversed() method works only on iterable objects like strings or lists.
2. Reverse the string using the reversed() method:
We apply the reversed() method to the string str_number. The reversed() function returns an iterator that produces the string's characters in reverse order. We then use ''.join()'' to join these characters back into a single string.
3. Convert the reversed string back to an integer:
After reversing the string, we convert it back to an integer using int(). This gives us the reversed number.
4. Print the reversed number:
Finally, we print the reversed number, which in this case is 1098.
Key Takeaways:
If you're looking for an alternative to string slicing, this method is a great option.
How to Reverse a Number in Python Using a List
Reversing a number in Python using a list is a simple and effective approach that builds on the concept of manipulating a sequence of digits.
Let’s break this process into clear steps.
#convert the number into a string
number = 45891
str_number = str(number)
#convert the string into a list of characters (digits)
digit_list = list(str_number)
#reverse the list using slicing
reversed_list = digit_list[::-1]
#join the reversed list into a string
reversed_str = ''.join(reversed_list)
#convert the reversed string back to an integer
reversed_number = int(reversed_str)
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 19854
Explanation:
1. Convert the number into a string:
The number 45891 is converted into a string using str(number). This allows you to treat each digit as an individual character.
2. Convert the string into a list of characters:
Using the list() function, the string is broken down into a list of its individual digits: ['4', '5', '8', '9', '1'].
3. Reverse the list using slicing:
The slicing technique [::-1] reverses the order of elements in the list. The result is ['1', '9', '8', '5', '4'].
4. Join the reversed list into a string:
Using ''.join(reversed_list), the reversed list of digits is combined back into a single string: "19854".
5. Convert the reversed string back to an integer:
Finally, the reversed string is converted back to an integer using int(). This ensures the output is a numeric value, not a string.
6. Print the reversed number:
The print() statement outputs the reversed number, which is 19854.
Key Takeaways:
How to Reverse a Number in Python Using a Stack
A stack in Python operates on the principle of Last In, First Out (LIFO), meaning the last element added is the first one removed. This behavior is crucial in many algorithms, especially those involving recursion, backtracking, or parsing expressions.
Let’s look at this step-by-step.
#convert the number into a string
number = 34567
str_number = str(number)
#initialize an empty stack
stack = []
#push each digit of the number into the stack
for digit in str_number:
stack.append(digit)
#pop digits from the stack to form the reversed string
reversed_str = ''
while stack:
reversed_str += stack.pop()
#convert the reversed string back to an integer
reversed_number = int(reversed_str)
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 76543
Explanation:
1. Convert the number into a string:
The number 34567 is converted into a string using str(number), so each digit can be processed individually.
2. Initialize an empty stack:
We use a Python list (stack = []) as a stack. Lists in Python allow us to mimic stack operations like push (append) and pop.
3. Push each digit into the stack:
Using a for loop, each digit from the string str_number is added to the stack with stack.append(digit). The stack now looks like this: ['3', '4', '5', '6', '7'].
4. Pop digits from the stack to form the reversed string:
Using a while loop, we repeatedly remove the top digit from the stack with stack.pop() and add it to reversed_str. The LIFO nature of the stack ensures the digits are retrieved in reverse order. The final reversed string is "76543".
5. Convert the reversed string back to an integer:
The reversed string is converted back to a number using int(reversed_str), ensuring the output is a numeric value.
6. Print the reversed number:
The print() statement outputs the reversed number, which is 76543.
Key Takeaways:
Try implementing this yourself! Stacks are a fundamental data structure in computer science, and this exercise is a great way to understand their practical application.
Also Read: How to Implement Stacks in Data Structure? Stack Operations Explained
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
Reversing a number in Python can be done in several ways, each with its unique advantages. From using string slicing for a quick and simple solution to applying recursion for a more advanced approach, or even manipulating lists to reverse the digits, each method serves a specific purpose depending on the task at hand.
While these techniques are straightforward once understood, many beginners still face challenges when deciding which method to use in different scenarios.
To help bridge this gap, upGrad’s personalized career guidance can help you explore the right learning path based on your goals. You can also visit your nearest upGrad center and start hands-on training today!
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!
References:
https://realpython.com/python-news-april-2025/
900 articles published
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources