Reversing a number—rearranging its digits so the last digit becomes the first and the first becomes the last—is one of the classic beginner exercises in Python. It shows up in coding interviews, palindrome checks, and algorithm challenges. This article walks through five different ways to do it, from the fastest one-liner to a full recursive solution, with edge case handling at every step.
Before jumping into code, it helps to understand what "reversing a number" actually means in programming terms. Given an integer like 12345, the goal is to produce 54321. Sounds simple, and it is—but the approach you choose depends on whether you value readability, performance, or interview-friendliness. Python gives you several clean ways to get there, and each one teaches you something different about the language.
String Slicing (The One-Liner)
The fastest and cleanest way to reverse a number in Python is to convert it to a string, apply slice notation with a step of -1, and convert it back to an integer. This takes advantage of Python's powerful slicing syntax where [::-1] means "start at the end, move to the beginning, one character at a time."
number = 12345
reversed_number = int(str(number)[::-1])
print(reversed_number)
# Output: 54321
Here is what happens at each step. First, str(number) converts the integer 12345 into the string "12345". Then, [::-1] reverses that string into "54321". Finally, int() converts it back to the integer 54321.
String slicing is the go-to method for quick scripts and everyday Python work. It is concise, readable, and fast enough for virtually any use case you will encounter outside of competitive programming.
If you want this wrapped in a reusable function:
def reverse_number(n):
return int(str(n)[::-1])
print(reverse_number(9876))
# Output: 6789
While Loop with Modulo Arithmetic
This is the approach that interviewers expect you to know. Instead of converting to a string, you extract digits one at a time using the modulo operator (%) and integer division (//). It builds the reversed number digit by digit using pure math.
number = 12345
reversed_number = 0
while number > 0:
digit = number % 10
reversed_number = reversed_number * 10 + digit
number //= 10
print(reversed_number)
# Output: 54321
Let's trace through this step by step with the input 12345:
- Iteration 1:
digit = 5,reversed_number = 0 * 10 + 5 = 5,number = 1234 - Iteration 2:
digit = 4,reversed_number = 5 * 10 + 4 = 54,number = 123 - Iteration 3:
digit = 3,reversed_number = 54 * 10 + 3 = 543,number = 12 - Iteration 4:
digit = 2,reversed_number = 543 * 10 + 2 = 5432,number = 1 - Iteration 5:
digit = 1,reversed_number = 5432 * 10 + 1 = 54321,number = 0
Once number reaches 0, the while loop exits and reversed_number holds the final result.
The modulo approach uses no string conversion at all. This makes it the preferred method in coding interviews because it demonstrates an understanding of how digit extraction works at a mathematical level.
Here is the same logic packaged as a clean function:
def reverse_number_math(n):
reversed_num = 0
while n > 0:
reversed_num = reversed_num * 10 + n % 10
n //= 10
return reversed_num
print(reverse_number_math(67890))
# Output: 9876
Notice that 67890 reversed becomes 9876 rather than 09876. That is because Python integers do not store leading zeros. We will cover this edge case in detail later in the article.
Recursion
Recursion reverses a number by peeling off the last digit with each function call and rebuilding the number as the calls return. It is a more structured approach that works well for learning how recursive thinking applies to digit manipulation.
def reverse_recursive(n, reversed_num=0):
if n == 0:
return reversed_num
return reverse_recursive(n // 10, reversed_num * 10 + n % 10)
print(reverse_recursive(12345))
# Output: 54321
Each call to reverse_recursive does two things: it strips the last digit from n by floor-dividing by 10, and it attaches that digit to reversed_num by multiplying by 10 and adding the extracted digit. When n reaches zero, the accumulated reversed_num is returned back through the call stack.
Python has a default recursion limit of 1,000 calls. For extremely large numbers (hundreds of digits), recursion will hit a RecursionError. Use the while loop or string slicing method for those cases instead.
Using reversed() and join()
Python's built-in reversed() function returns an iterator that yields characters in reverse order. Combined with join(), it provides another readable approach to reversing a number.
number = 12345
reversed_number = int(''.join(reversed(str(number))))
print(reversed_number)
# Output: 54321
In this method, str(number) converts the integer to a string, reversed() creates a reverse iterator over that string's characters, and ''.join() concatenates them back into a single string. The final int() call converts the result back to an integer.
This approach is slightly more verbose than the slicing one-liner, but it reads clearly and works well when you want to perform additional processing on each digit before joining them. For example, you could filter or transform digits inside a generator expression before calling join().
Handling Edge Cases
The basic examples above all assume a positive integer with no special conditions. Real-world code needs to account for negative numbers, trailing zeros, and single-digit inputs. Here is a robust function that handles all of these:
def reverse_number_safe(n):
if n < 0:
return -int(str(-n)[::-1])
return int(str(n)[::-1])
# Negative numbers
print(reverse_number_safe(-1234))
# Output: -4321
# Trailing zeros become leading zeros (dropped by int)
print(reverse_number_safe(1200))
# Output: 21
# Single digit
print(reverse_number_safe(7))
# Output: 7
Negative Numbers
When a number is negative, you cannot just reverse the entire string because the minus sign would end up at the wrong end. The solution is to strip the sign, reverse the absolute value, and then reattach the negative sign. In the function above, str(-n) converts -1234 to the string "1234", reverses it to "4321", and the leading - is reapplied after conversion.
Trailing Zeros
Reversing 1200 produces the string "0021". When you convert that back to an integer with int(), Python automatically drops the leading zeros, giving you 21. This is standard integer behavior—there is no way to preserve leading zeros in a Python int. If you need to keep them for display purposes, store the result as a string instead.
The Modulo Approach with Negative Numbers
If you prefer the mathematical method, wrap it to handle the sign separately:
def reverse_math_safe(n):
negative = n < 0
n = abs(n)
reversed_num = 0
while n > 0:
reversed_num = reversed_num * 10 + n % 10
n //= 10
return -reversed_num if negative else reversed_num
print(reverse_math_safe(-5678))
# Output: -8765
Comparing All Methods
Each method has its own strengths. Here is a side-by-side comparison to help you choose the right one for your situation:
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| String slicing | O(d) | O(d) | Quick scripts, readability |
| While loop (modulo) | O(d) | O(1) | Interviews, memory efficiency |
| Recursion | O(d) | O(d) | Learning recursion concepts |
| reversed() + join() | O(d) | O(d) | Readability, digit processing |
In this table, d represents the number of digits in the input number. All methods run in linear time relative to the digit count. The key difference is space: the while loop method operates in constant space because it never creates a string copy of the number, while the others allocate memory proportional to the number of digits.
For coding interviews, go with the while loop and modulo approach. It shows you understand digit extraction without leaning on Python-specific string tricks. For production code where readability matters, string slicing is the standard choice.
Key Takeaways
- String slicing with
[::-1]is the simplest approach. Convert to a string, reverse it, convert back. One line, clean and readable. - The while loop with
% 10and// 10is the interview standard. It demonstrates digit-level manipulation without string conversion and uses constant memory. - Recursion is elegant but has limits. Python's default recursion depth of 1,000 calls means this approach is best suited for learning, not for handling arbitrarily large numbers.
- Always handle edge cases. Negative numbers need their sign preserved separately. Trailing zeros in the original number become leading zeros in the reversed result, and Python integers drop those automatically.
- Choose your method based on context. Everyday scripting favors readability (string slicing). Interview settings favor the mathematical approach. Recursive solutions are best for practicing recursion itself.
Reversing a number is a small problem, but it packs a surprising amount of Python knowledge into a few lines of code. You practice type conversion, slicing syntax, modular arithmetic, and recursive thinking all in one exercise. Once you are comfortable with all five approaches here, you will have the tools to tackle related problems like palindrome detection, digit sum calculations, and number-based algorithm challenges with confidence.