How to reverse a number in Python
Learn to reverse a number in Python. Explore different methods, tips, real-world applications, and how to debug common errors.

To reverse a number in Python is a classic problem that appears in many technical interviews. It's a great way to demonstrate your logic and your knowledge of operators like // and %.
You'll learn several methods, from iterative loops to concise string slicing. You'll also get practical tips, see real-world use cases, and find advice to debug your code.
Basic number reversal with string conversion
num = 12345
reversed_num = int(str(num)[::-1])
print(f"Original: {num}, Reversed: {reversed_num}")--OUTPUT--Original: 12345, Reversed: 54321
This method is popular for its brevity and readability. It cleverly sidesteps mathematical operations by treating the number as text. First, str(num) converts the integer into a string, making it accessible to Python's powerful slicing tools.
The core of this technique is the slice notation [::-1]. This is a common Python idiom that creates a reversed copy of any sequence, including strings. Once the character order is flipped, int() converts the new string back into a number, completing the reversal. It's an elegant solution, though it does involve the overhead of type casting.
String-based techniques
Beyond the simple slice, you can break down the reversal process into more explicit steps using tools like the reversed() function or a list comprehension.
Breaking down string reversal steps
num = 7890
num_str = str(num)
reversed_str = num_str[::-1]
reversed_num = int(reversed_str)
print(reversed_num)--OUTPUT--987
This example breaks the reversal process into explicit variables for clarity. It also highlights an important side effect of string conversion—what happens to trailing zeros. When 7890 is reversed as a string, it becomes 0987.
- The number is first converted to a string using
str(). - Slicing with
[::-1]reverses the string's characters. - Finally, the
int()function converts"0987"back to a number, automatically dropping the leading zero to produce987.
Using the reversed() function
num = 12345
reversed_str = ''.join(reversed(str(num)))
reversed_num = int(reversed_str)
print(reversed_num)--OUTPUT--54321
The reversed() function offers a more explicit alternative to slicing. It takes any sequence, like a string, and returns a reverse iterator—an object that yields items one by one, from last to first. Because it doesn't produce a string directly, you need an extra step to reassemble the characters.
- The
''.join()method is used to stitch the characters from the iterator back into a single string. - Then,
int()converts this new string into the final reversed number.
Using list comprehension
num = 9876
num_str = str(num)
reversed_str = ''.join([num_str[i] for i in range(len(num_str)-1, -1, -1)])
reversed_num = int(reversed_str)
print(reversed_num)--OUTPUT--6789
A list comprehension gives you fine-grained control over the reversal process. This method manually iterates through the string's indices, but in reverse order. It's more verbose than slicing but clearly shows the logic of walking backward through the string.
- The
range()function generates the indices, starting from the last character (len(num_str)-1) down to0. - The comprehension builds a list of characters in this new, reversed order.
- Finally,
''.join()stitches them together into the final string before conversion.
Mathematical approaches
While string conversions are straightforward, reversing a number with pure mathematics avoids type casting and can be more performant.
Using division and modulo operations
def reverse_number(num):
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
return reversed_num
print(reverse_number(12345))--OUTPUT--54321
This approach uses a while loop to dismantle the number digit by digit. It’s a purely mathematical solution that avoids any string conversions, building the reversed number iteratively.
- The modulo operator (
% 10) peels off the last digit of the original number. - The core logic,
reversed_num = reversed_num * 10 + digit, shifts the current reversed number one decimal place to the left and adds the new digit. - Floor division (
// 10) then removes the last digit from the original number, preparing for the next loop cycle.
Using recursion
def reverse_recursive(num, reversed_num=0):
if num == 0:
return reversed_num
return reverse_recursive(num // 10, reversed_num * 10 + num % 10)
print(reverse_recursive(12345))--OUTPUT--54321
Recursion offers an elegant way to solve this problem by breaking it down into smaller, self-similar tasks. The reverse_recursive function calls itself repeatedly, with each call handling one digit, until it reaches a stopping condition. The function's logic relies on two key parts:
- A base case,
if num == 0, which ends the recursion and returns the final reversed number. - A recursive step that calls the function again with a smaller
num(num // 10) and an updated accumulator that builds the reversed number.
Using functional programming with reduce()
from functools import reduce
def reverse_functional(num):
return reduce(lambda acc, digit: acc * 10 + int(digit), str(num)[::-1], 0)
print(reverse_functional(12345))--OUTPUT--54321
For a more functional style, you can use reduce() from the functools module. This function applies a rolling computation to a sequence, condensing it into a single value. It's a powerful way to express the reversal logic in one line.
- The code first converts the number to a string and reverses it.
reduce()then iterates over each character of the reversed string, starting with an initial value of0.- A
lambdafunction provides the logic, using an accumulator (acc) to build the new number with the same math—acc * 10 + int(digit)—as the loop-based method.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
The number reversal techniques in this article, from simple string slicing to mathematical loops, are the building blocks for real-world tools. Replit Agent can turn these concepts into production applications directly from a description.
- Build a palindrome checker API that validates numerical inputs by comparing them to their reversed form.
- Create a data transformation utility that reverses product serial numbers for legacy system compatibility.
- Deploy an interactive tool that visualizes how the
%and//operators deconstruct and rebuild numbers.
Turn your concept into a live application. Describe your project and let Replit Agent write, test, and deploy the code for you.
Common errors and challenges
Reversing numbers seems straightforward, but a few common pitfalls can trip you up, especially when dealing with zeros and negative signs.
- When you reverse a number like
12300using string methods, you get the string"00321". Converting this back to a number withint()results in321, because Python discards the mathematically insignificant leading zeros. This is usually the desired outcome for numerical problems, but it’s something to watch out for if the exact digit sequence is important. - Negative numbers introduce another wrinkle. A simple string reversal on
-123would produce"321-", which causes an error when you try to convert it back to an integer. The standard approach is to handle the sign separately. You can use theabs()function to get the positive version of the number, reverse it, and then reapply the negative sign to the final result. - If you need to preserve trailing zeros from the original number—which become leading zeros in the reversed version—you must avoid converting the reversed string back to an integer. For example, if reversing
9870must result in0789, your final output should be the string"0789". The moment you useint(), those leading zeros vanish.
Handling leading zeros in reversed numbers
When a number with trailing zeros like 1020 is reversed, the int() function's behavior can be surprising. It discards the new leading zeros, altering the number's structure in a way you might not expect. The code below shows this in action.
num = 1020
reversed_num = int(str(num)[::-1])
print(f"Original: {num}, Reversed: {reversed_num}")
The output is 201 because reversing 1020 creates the string "0201". The int() function then removes the leading zero, altering the result. The code below demonstrates a way to manage this behavior.
num = 1020
reversed_str = str(num)[::-1]
print(f"Original: {num}, Reversed as string: {reversed_str}, As number: {int(reversed_str)}")
The solution is to simply keep the reversed number as a string. After reversing 1020 with str(num)[::-1] to get "0201", you just don't convert it back with int(). This preserves the leading zero. It's a necessary step when the exact digit sequence is the data—like with serial numbers or specific data formats—and not its mathematical value. This way, you retain the full reversed representation.
Handling negative numbers with abs() function
Reversing negative numbers with simple string slicing creates an invalid format. When you reverse -12345, the string becomes "54321-", which the int() function can't parse. This triggers a ValueError because the minus sign is at the end. The code below demonstrates this problem in action.
num = -12345
reversed_num = int(str(num)[::-1])
print(f"Original: {num}, Reversed: {reversed_num}")
The str() conversion includes the negative sign, so slicing [::-1] moves it to the end. The resulting string, "54321-", is an invalid format for the int() function, causing a ValueError. See how to fix this below.
num = -12345
abs_num = abs(num)
reversed_abs = int(str(abs_num)[::-1])
reversed_num = -reversed_abs if num < 0 else reversed_abs
print(f"Original: {num}, Reversed: {reversed_num}")
The correct approach is to handle the sign separately from the digits. This avoids the ValueError that occurs when the minus sign ends up at the end of the string.
- First, use the
abs()function to get the number's positive value. - Next, reverse this positive number using your preferred method, like string slicing.
- Finally, use a conditional to check if the original number was negative and reapply the sign to the reversed result.
Preserving trailing zeros when using int() conversion
Reversing a number with trailing zeros, like 12300, can be tricky. The int() function will discard the resulting leading zeros, altering the number's structure. This isn't always the desired behavior, especially if the digit sequence is important. See what happens below.
num = 12300
reversed_num = int(str(num)[::-1])
print(f"Original: {num}, Reversed: {reversed_num}")
The code produces 321, dropping the trailing zeros from the original number. This happens because int() treats the reversed string 00321 as a mathematical value, not a sequence of digits. Check out the following code for an alternative.
num = 12300
reversed_str = str(num)[::-1]
print(f"Original: {num}, Reversed as string: {reversed_str}, As number: {int(reversed_str)}")
The solution is to treat the reversed number as text. By avoiding the final int() conversion, you can preserve the complete digit sequence.
- The reversed string
"00321"accurately reflects all digits from the original12300. - This is crucial for non-mathematical data like product IDs, where every digit matters.
- Keeping the result as a string is the only way to prevent Python from dropping the leading zeros.
Real-world applications
Reversing numbers isn't just a coding puzzle; it's a key step in applications like palindrome detection and basic data encoding.
Checking if a number is a palindrome using str() comparison
You can quickly determine if a number is a palindrome by converting it to a string and checking if it's identical to its reversed version.
def is_palindrome(num):
return str(num) == str(num)[::-1]
test_numbers = [121, 12321, 12345, 98789]
for num in test_numbers:
print(f"{num} is{' ' if is_palindrome(num) else ' not '}a palindrome")
This solution's elegance comes from the is_palindrome function, which uses a single expression to return a boolean value. It capitalizes on Python's string slicing ([::-1]) to create a reversed version of the number for a direct comparison.
The for loop then demonstrates a neat trick for conditional formatting inside an f-string. The expression {' ' if is_palindrome(num) else ' not '} inserts text based on the function's True or False return, producing a clean, dynamic output for each number tested.
Creating a simple number encoding scheme with [::-1] reversal
You can use number reversal as the first step in a simple encoding scheme, combining it with a mathematical 'salt' to obscure data like account IDs.
def encode_number(num, salt=7):
reversed_num = int(str(num)[::-1])
encoded = reversed_num * salt + salt
return encoded
account_id = 12345
encoded_id = encode_number(account_id)
print(f"Original ID: {account_id}, Encoded: {encoded_id}")
The encode_number function shows how to create a simple data transformation. It takes a number and a 'salt' value to generate a new, less predictable number. The logic's straightforward:
- First, it reverses the input number using the familiar string slicing technique.
- Then, it applies a basic mathematical formula. It multiplies the reversed number by the
saltand adds thesaltagain, producing the final encoded value. This makes the output harder to trace back to the original without knowing the formula.
Get started with Replit
Put these techniques into practice. Describe a tool to Replit Agent, like “a palindrome number checker API” or “a utility to reverse product serial numbers for a database.”
The agent handles the coding, testing, and deployment, turning your prompt into a finished application. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)