Check if a Number is a Palindrome in Python

"Numbers also have symmetry, and palindromes show us that logic can be as elegant as a perfect reflection."

A palindrome number is one that reads the same from left to right and from right to left.
Examples of palindrome numbers:

  • 121
  • 12321
  • 4004

In this tutorial, you will learn how to check if a number is a palindrome in Python using several approaches.

Method 1: Convert the Number to a String

The simplest way is to convert the number to a string and compare it with its reversed version.

def is_palindrome_number(n: int) -> bool:
    return str(n) == str(n)[::-1]

print(is_palindrome_number(121))    # True
print(is_palindrome_number(12345))  # False
print(is_palindrome_number(4004))   # True

Advantages:

  • Easy to understand.
  • Commonly used in coding interviews.

Method 2: Using Mathematical Operations

If you don’t want to convert to a string, you can reverse the number using division and modulus.

def is_palindrome_number_math(n: int) -> bool:
    original = n
    reversed_num = 0
    while n > 0:
        reversed_num = reversed_num * 10 + n % 10
        n //= 10
    return original == reversed_num

print(is_palindrome_number_math(12321))  # True
print(is_palindrome_number_math(12345))  # False

Advantages:

  • Avoids string conversions.
  • Useful when aiming for algorithmic efficiency.

Method 3: Using Slicing with Strings

A shorter version of the first method, ideal for simple cases.

print(str(12321) == str(12321)[::-1])  # True

Considerations

  • Negative numbers are usually not considered palindromes, since the - sign breaks symmetry.
  • In interview problems (e.g., LeetCode), leading zeros also tend to invalidate palindromes (example: 010 is not valid).
  • It’s best to choose the method depending on whether you prioritize simplicity (strings) or optimization (mathematics).

Checking whether a number is a palindrome in Python is a very common exercise in algorithm practice and technical interviews.

  • Quick method: string conversion.
  • Mathematical method: reverse the number without strings.
  • Practical use: strengthen data manipulation and control structure concepts.

With these examples, you can now detect palindromes in numbers simply and efficiently.

You may also be interested in: