How to reverse a number in Python

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

How to reverse a number in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

To reverse a number in Python is a fundamental task for developers who work with numerical data. Python's logic and built-in functions provide straightforward methods for this common programming challenge.

In this article, we'll cover several techniques to reverse numbers. We'll also share practical tips, real-world applications, and debugging advice to help you master the different approaches for your projects.

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 approach is popular for its readability and conciseness. Since integers aren't inherently reversible sequences, the strategy is to convert the number to a string. This lets you leverage Python's powerful sequence manipulation tools.

The core of this technique is the slice notation [::-1]. It's a clean, Pythonic way to reverse any sequence, including our temporary string. The process is simple:

  • Convert the number to a string with str().
  • Reverse the string using the [::-1] slice.
  • Convert the reversed string back to an integer with int().

String-based techniques

While the [::-1] slice is a concise one-liner, other string-based techniques offer more granular control or alternative syntax for achieving the same reversal.

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

Breaking the process into separate lines can make the logic easier to follow. Each step—converting to a string, reversing it, and converting back to an integer—is explicitly assigned to a variable for clarity.

  • The number is first converted to a string with str().
  • Next, the [::-1] slice reverses the string.
  • Finally, int() converts the string back to a number. Notice how it automatically handles the leading zero from the original number's trailing zero, resulting in the integer 987.

Using the reversed() function

num = 12345
reversed_str = ''.join(reversed(str(num)))
reversed_num = int(reversed_str)
print(reversed_num)--OUTPUT--54321

Another way to reverse the string is with Python's built-in reversed() function. Unlike slicing, this function doesn't return a string directly. Instead, it gives you an iterator that yields characters in reverse order. You then need to reassemble these characters into a string.

  • The reversed() function creates a reverse iterator from the number's string representation.
  • The ''.join() method takes this iterator and concatenates its elements into a single new string.
  • Finally, int() converts the resulting string back into a 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

List comprehension offers a more explicit, step-by-step way to build a reversed sequence. This method constructs a new list of characters by iterating through the original string's indices in reverse order.

  • The range() function generates indices from the last character down to the first. Specifically, range(len(num_str)-1, -1, -1) creates a sequence of indices like 3, 2, 1, 0 for a four-character string.
  • The list comprehension then builds a list of characters in reverse.
  • Finally, ''.join() combines these characters into a string, which is then converted back to an integer with int().

Mathematical approaches

Alternatively, you can skip string conversion and reverse a number using mathematical logic, from simple division and modulo operations to recursion or reduce().

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 purely mathematical approach uses a while loop to deconstruct and rebuild the number. The logic iteratively peels off the last digit from the original number and uses it to construct the new, reversed number until the original is reduced to zero.

  • The modulo operator (% 10) isolates the last digit of num.
  • This digit is then appended to reversed_num, which is first multiplied by 10 to shift its existing digits to the left.
  • Floor division (// 10) effectively removes the last digit from num 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, mathematical solution by breaking the problem into smaller, identical subproblems. The reverse_recursive function calls itself repeatedly, processing one digit at a time until the original number is reduced to zero. This type of intuitive, exploratory programming is at the heart of vibe coding.

  • The base case, if num == 0, is the condition that stops the recursion and returns the final, accumulated result.
  • In each recursive step, the function calls itself with a smaller version of the number (num // 10) and an updated reversed number (reversed_num * 10 + num % 10).

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

The reduce() function from the functools module offers a compact, functional way to perform this calculation. It works by applying a function cumulatively to the items of a sequence, reducing the sequence to a single final value.

  • This approach first converts the number to a string and reverses it with str(num)[::-1].
  • reduce() then iterates over each character (digit) in this reversed string.
  • The lambda function, lambda acc, digit: acc * 10 + int(digit), rebuilds the number mathematically, starting with an initial accumulator value of 0.

Move faster with Replit

Replit is an AI-powered development platform where all Python dependencies are pre-installed, so you can skip setup and start coding instantly. While mastering individual techniques like number reversal is essential, the next step is applying them to build complete applications. This is where Agent 4 comes in. It takes your project idea and handles the entire development process—from writing code and connecting to APIs to managing deployment.

Instead of just piecing together functions, you can describe the app you want to build, and Agent 4 will take it from concept to a working product. For example, you could build:

  • A palindrome checker tool that uses number reversal to verify if a number reads the same forwards and backward.
  • A data anonymizer that reverses numerical user IDs to create non-identifiable data for testing environments.
  • A custom calculator that uses division and modulo logic, similar to the mathematical reversal method, to perform specific base conversions.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Reversing numbers in Python can introduce subtle bugs, especially when dealing with negative values or zeros. These issues often require code repair techniques to handle edge cases properly.

  • Handling negative numbers: String-based reversal on a negative number like -123 produces "321-", which causes a ValueError during integer conversion. To fix this, you can use the abs() function to work with the number's positive value and reapply the negative sign after the reversal is complete.
  • Losing trailing zeros: When you reverse a number ending in zero, like 5400, it becomes "0045" as a string. The int() function correctly interprets this as 45, dropping the leading zeros. This is expected, but if you need to preserve those zeros for display or formatting, you should keep the result as a string.

Handling leading zeros in reversed numbers

Reversing a number like 1020 presents a specific challenge with zeros. The trailing zero becomes a leading zero, which the int() function automatically drops. This can alter the expected output if you are not careful. See how this plays out below.

num = 1020
reversed_num = int(str(num)[::-1])
print(f"Original: {num}, Reversed: {reversed_num}")

The code reverses 1020 into the string "0201". The int() function then interprets this as 201, dropping the leading zero and altering the number's structure. The following example shows how to handle this.

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 keep the reversed number as a string if you need to preserve leading zeros. The code demonstrates that the reversed_str variable correctly holds "0201". It's only when you convert it back with int() that the leading zero is dropped, resulting in 201. This distinction is crucial in tasks where the exact digit sequence matters, like formatting identifiers or when the reversed number is for display purposes only.

Handling negative numbers with abs() function

Handling negative numbers with abs() function

Reversing negative numbers with string slicing introduces a unique problem. The negative sign ends up at the end of the string, like in "123-". When you try converting this back to a number, Python's int() function can't parse it.

The code below demonstrates how this simple reversal attempt will fail and raise a ValueError.

num = -12345
reversed_num = int(str(num)[::-1])
print(f"Original: {num}, Reversed: {reversed_num}")

The issue is that str(num)[::-1] reverses the entire string representation to "54321-". The int() function expects the sign at the beginning, not the end, causing the conversion to fail. Here's how to fix it.

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 solution is to handle the sign separately. First, use the abs() function to get the number’s positive value. After reversing this absolute number, you can use a conditional check to reapply the negative sign if the original number was negative. This ensures the sign is correctly placed at the beginning of the number, which avoids the ValueError that would otherwise occur when converting a string like "54321-" to an integer.

Preserving trailing zeros when using int() conversion

Preserving trailing zeros when using int() conversion

When you reverse a number with trailing zeros, the int() function's behavior can be unexpected. It automatically drops the leading zeros from the reversed string, which can alter the result if you need to preserve the number's original structure.

The code below demonstrates how this happens.

num = 12300
reversed_num = int(str(num)[::-1])
print(f"Original: {num}, Reversed: {reversed_num}")

The reversed string "00321" is converted to the integer 321 because the int() function discards leading zeros, altering the number's structure. The following code demonstrates how to approach this challenge.

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 work with the reversed string directly if you need to preserve the zeros. The code demonstrates this by storing the reversed sequence as reversed_str, which correctly holds "00321". This is crucial for tasks like formatting identifiers or when the reversed number is for display. Only convert back to an integer with int() if you intend to perform mathematical operations and can accept the loss of leading zeros.

Real-world applications

Beyond the technical challenges, reversing numbers has practical uses in areas like data validation and simple encoding schemes.

Checking if a number is a palindrome using str() comparison

You can check if a number is a palindrome (one that reads the same forwards and backward) by comparing its str() representation 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")

The is_palindrome function provides a concise solution by leveraging string manipulation. It returns a boolean value based on a simple comparison.

  • The function converts the number to a string using str().
  • It then compares this string to its reversed version, which is generated with the slice notation [::-1].
  • The loop demonstrates this by using an f-string's conditional expression to print whether each number in test_numbers is a palindrome.

Creating a simple number encoding scheme with [::-1] reversal

You can combine the [::-1] reversal technique with simple arithmetic to create a basic encoding scheme for obscuring numerical data like internal 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 transforms a number using both reversal and arithmetic. It takes an input num and an optional salt value, which defaults to 7. The function's logic is straightforward:

  • First, it reverses the number using the str(num)[::-1] technique.
  • Next, it multiplies this reversed number by the salt and then adds the salt again.

This process creates a new, transformed number from the original. Using the salt parameter lets you adjust the transformation's output, making the function's result customizable.

Get started with Replit

Now, use these techniques to build something. Tell Replit Agent: "Build a web app that checks if a number is a palindrome" or "Create a Python script that reverses user IDs for data anonymization."

The Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.