Check if a Number is a Palindrome in Python

A palindrome number is a number that remains the same when its digits are reversed. For example, 121, 1331, and 12321 are palindrome numbers, while 123 and 456 are not. In this blog, we’ll explore how to check if a number is a palindrome using Python.


What Is a Palindrome Number?

A number nn is a palindrome if: reverse(n)=n\text{reverse}(n) = n

For instance:

  • 121 reversed is 121 → Palindrome ✅
  • 123 reversed is 321 → Not a palindrome ❌

Method 1: Using String Manipulation

The simplest way to check if a number is a palindrome is to convert it to a string and compare it with its reverse.

Code Example:

# Check if a number is a palindrome using string manipulation
def is_palindrome(number):
    # Convert the number to a string
    str_num = str(number)
    # Check if the string is equal to its reverse
    return str_num == str_num[::-1]

# Example usage
number = 121
if is_palindrome(number):
    print(f"{number} is a palindrome")
else:
    print(f"{number} is not a palindrome")

Explanation:

  1. Convert the number to a string using str(number).
  2. Reverse the string using slicing ([::-1]).
  3. Compare the original string with its reverse.

Output:

121 is a palindrome

Method 2: Using a Mathematical Approach

This method avoids string manipulation by reversing the number mathematically.

Code Example:

# Check if a number is a palindrome using a mathematical approach
def is_palindrome(number):
    original = number
    reverse = 0

    while number > 0:
        digit = number % 10  # Get the last digit
        reverse = reverse * 10 + digit  # Append digit to reverse
        number = number // 10  # Remove the last digit

    return original == reverse

# Example usage
number = 12321
if is_palindrome(number):
    print(f"{number} is a palindrome")
else:
    print(f"{number} is not a palindrome")

Explanation:

  1. Extract the last digit of the number using number % 10.
  2. Append it to the reverse number using reverse = reverse * 10 + digit.
  3. Remove the last digit from the number using integer division (number //= 10).
  4. Compare the original number with the reversed number.

Output:

12321 is a palindrome

Method 3: Using Recursion

You can also use recursion to check if a number is a palindrome.

Code Example:

# Check if a number is a palindrome using recursion
def is_palindrome_recursive(number, reverse=0, original=None):
    if original is None:
        original = number

    if number == 0:
        return original == reverse

    digit = number % 10
    reverse = reverse * 10 + digit
    return is_palindrome_recursive(number // 10, reverse, original)

# Example usage
number = 454
if is_palindrome_recursive(number):
    print(f"{number} is a palindrome")
else:
    print(f"{number} is not a palindrome")

Explanation:

  1. Base case: If number becomes 0, compare the reverse with the original.
  2. Recursive step: Extract the last digit, update reverse, and call the function with the reduced number.

Output:

454 is a palindrome

Handling Edge Cases

  1. Negative Numbers:
    • Negative numbers are not considered palindromes because the minus sign (-) does not have a corresponding reverse.
    • Example: -121 → Not a palindrome.
    number = -121 print(f"{number} is not a palindrome") # Output: -121 is not a palindrome
  2. Single-Digit Numbers:
    • All single-digit numbers are palindromes.
    • Example: 7 → Palindrome.
  3. Zero:
    • 0 is a palindrome as reversing it gives the same value.

Comparison of Methods

MethodUse CaseEfficiency
String ManipulationSimple and quick for small numbersHigh
Mathematical ApproachAvoids string conversion, memory-efficientHigh
Recursive MethodEducational or when recursion is preferredModerate

Conclusion

In this blog, we explored multiple ways to check if a number is a palindrome in Python:

  1. String Manipulation: Ideal for quick checks.
  2. Mathematical Approach: Best for memory efficiency.
  3. Recursive Method: A functional and recursive way to solve the problem.

Choose the method that best fits your use case and keep practicing to master Python! 🚀


Share with our team

Leave a Comment