How To Check Palindrome Number in Python?
By Rohit Sharma
Updated on Jun 24, 2025 | 10 min read | 16.28K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Jun 24, 2025 | 10 min read | 16.28K+ views
Share:
Do you know? In the range from 171 to 115,000, there are 10,008 palindrome numbers, all of which can be identified using a simple Python one-liner that checks if a number reads the same forwards and backwards. |
Finding palindrome number in Python is a fundamental task in programming, often used to check data integrity, such as verifying whether a word, number, or sequence remains the same when reversed. This concept is particularly important in fields like data validation and DNA sequence analysis.
For example, checking if a product ID or customer code is a palindrome ensures it meets specific criteria for symmetric representation.
In this blog, we’ll explore various ways to check palindrome number in Python, including both numeric and string-based methods.
Checking whether a given string, number, or sequence is a palindrome is a common task in programming. A palindrome is a word, number, or sequence of characters that reads the same backward as it reads forward.
For instance, words like "madam" and numbers like 12321 are palindromes, while "python" is not. In Python, there are several ways to check if a given input is a palindrome, ranging from simple approaches to more advanced methods.
In 2025, professionals who can use advanced programming techniques to streamline business operations will be in high demand. If you're looking to develop skills in in-demand programming languages, here are some top-rated courses to help you get there:
Now, let’s walk through various methods step by step for checking palindromes in Python, starting from basic approaches to more efficient solutions.
This is the most straightforward method to check palindrome number in Python. The idea is simple: reverse the number and compare it to the original number. If they are the same, the number is a palindrome; otherwise, it is not.
Here are the steps:
Example Code:
number = int(input("Enter a number: "))
reverse = 0
while number > 0:
digit = number % 10 # Extract the last digit
reverse = reverse * 10 + digit # Build the reversed number
number = number // 10 # Remove the last digit from the number
# Check if the reversed number is equal to the original number
if number == reverse:
print("It is a palindrome!")
else:
print("It is not a palindrome!")
Explanation:
Input:
Enter a number: 121
Output:
It is a palindrome!
Note: Although effective, this approach has more lines of code and is less readable compared to other more efficient methods.
Also Read: Python Cheat Sheet: From Fundamentals to Advanced Concepts for 2025
In Python, you can leverage string slicing to reverse a string and compare it with the original string in just one line. This method is efficient and concise, making it a popular choice for checking palindrome number in Python.
Here are the steps:
Example Code:
number = input("Enter a number: ")
# Reverse the string using slicing and check for equality
if number == number[::-1]:
print("It is a palindrome!")
else:
print("It is not a palindrome!")
Explanation:
Input:
Enter a number: 121
Output:
It is a palindrome!
Note: This is a one-liner solution that is highly readable and efficient for most use cases.
Also Read: Top 36+ Python Projects for Beginners and Students to Explore in 2025
For those interested in a more algorithmic approach, recursion can be used to check whether a string or list is a palindrome by comparing the first and last characters, and then recursively checking the next pair of characters.
Here are the steps:
Example Code:
def isPalindrome(numbers, start, end):
if start >= end: # Base case: single character or empty string
return True
if numbers[start] == numbers[end]: # Compare first and last characters
return isPalindrome(numbers, start + 1, end - 1) # Recursive call
else:
return False # If characters do not match, it is not a palindrome
# Example usage
numbers = list(input("Enter a string: "))
n = len(numbers)
if isPalindrome(numbers, 0, n - 1):
print("It is a palindrome!")
else:
print("It is not a palindrome!")
Explanation:
Input:
Enter a string: radar
Output:
It is a palindrome!
Note: This method is ideal for those looking for a recursive solution and provides a deeper understanding of problem-solving using recursion.
Also Read: Career Opportunities in Python: Complete Guide for 2025
Python's built-in reversed() function can be used to reverse a string or list and check if it matches the original. This method is simple and clean, making it a great choice for checking palindrome number in Python.
Here are the steps:
Example Code:
number = input("Enter a number: ")
# Use reversed() and join() to check for palindrome
if number == ''.join(reversed(number)):
print("It is a palindrome!")
else:
print("It is not a palindrome!")
Explanation:
Input:
Enter a number: madam
Output:
It is a palindrome!
Note: This is an elegant and efficient method to check for palindrome using Python’s built-in capabilities.
You can get a better understanding of Python integration with upGrad’s Learn Python Libraries: NumPy, Matplotlib & Pandas. Learn how to manipulate data using NumPy, visualize insights with Matplotlib, and analyze datasets with Pandas.
Also Read: Top 15 Python Challenges for Beginners with Examples
Another approach is to use a for loop to manually compare characters from the beginning and end of the string, moving towards the center. This method is useful when you want full control over the comparison process.
Step-by-Step Process:
Example Code:
s = input("Enter a string: ")
def palindrome(s):
s = s.lower().replace(' ', '') # Convert to lowercase and remove spaces
reversed_string = ''
# Build the reversed string manually
for i in range(len(s)-1, -1, -1):
reversed_string += s[i]
return s == reversed_string # Return True if the string is a palindrome
if palindrome(s):
print("It is a palindrome!")
else:
print("It is not a palindrome!")
Explanation:
Input:
Enter a string: A man a plan a canal Panama
Output:
It is a palindrome!
Depending on your use case, each method provides a different balance of efficiency and readability.
Are you a full-stack developer wanting to integrate AI into your workflow? upGrad’s AI-Driven Full-Stack Development bootcamp can help you. You’ll learn how to build AI-powered software using OpenAI, GitHub Copilot, Bolt AI & more.
Also Read: How to Start Learning Python for Data Science in 2025
Next, let’s look at some tips you can follow when checking palindrome number in Python with the above methods.
When checking for palindrome number in Python, following best practices is essential for writing efficient, readable, and reliable code. You must ensure that your palindrome check is optimized for performance, works across different scenarios, and handles edge cases correctly. This can save time, reduce errors, and make your code more maintainable.
Using Python’s built-in capabilities effectively, handling case sensitivity, and dealing with non-alphanumeric characters are all vital steps to ensure your solution is robust and applicable in real-world applications.
Here are some best practices you need to keep in mind when checking palindrome number in Python:
One common pitfall when checking for palindromes is not considering the case sensitivity of characters. Python compares characters exactly as they appear, so without normalization, a character like 'A' would not be equal to 'a'. This can cause incorrect results when checking for palindromes, especially in user input.
Tip: Convert the string to lowercase using .lower() to ensure that 'A' and 'a' are treated as the same character.
s = s.lower() # Converts to lowercase for case-insensitive comparison
Why it's necessary? Ensuring case insensitivity guarantees that your function works in scenarios where input may have mixed case (such as "Madam" vs "madam").
In practical applications, palindromes might involve phrases or strings with spaces, punctuation, or special characters (e.g., "A man, a plan, a canal, Panama"). If these characters are not removed, they will interfere with the palindrome check, leading to incorrect results.
Tip: Use .replace() or regular expressions to remove spaces and punctuation before checking the palindrome number in Python.
import re
s = re.sub(r'[^a-zA-Z0-9]', '', s) # Removes non-alphanumeric characters
Why it's necessary? For phrases or strings with special characters, removing non-alphanumeric characters ensures that the palindrome check is focused solely on the relevant content (letters and numbers).
When working with large strings or data, efficiency becomes a key factor. The slicing method ([::-1]) is optimized in Python for reversing strings and comparing them, which makes it a better choice compared to using loops or recursion in terms of both speed and code simplicity.
Tip: Use slicing to reverse the string and compare it in one line for better readability and performance.
if s == s[::-1]: # Compare the string with its reverse using slicing
print("It is a palindrome!")
Why it's necessary? In applications where performance is crucial (e.g., processing large datasets or real-time data), using Python's efficient built-in operations like slicing minimizes computational overhead and maximizes performance.
Recursion can provide a deeper understanding of the problem-solving process, especially when learning to break down problems into smaller subproblems. However, for large strings, recursion might not be the most efficient due to potential stack overflow issues. It's an excellent tool for learning but should be used carefully for large datasets.
Tip: Use recursion to compare the first and last characters and then narrow the problem to the inner substring.
def is_palindrome_recursive(s, start, end):
if start >= end:
return True
if s[start] == s[end]:
return is_palindrome_recursive(s, start + 1, end - 1)
return False
Why it's necessary? While recursion may not always be the most efficient for palindrome checking, it encourages the development of recursive thinking and can be a good learning tool for those new to algorithms.
For numeric inputs, converting the number to a string allows you to use the same logic for checking palindromes as with strings. This is both efficient and simplifies the code, eliminating the need for additional logic when dealing with numbers.
Tip: Use str() to convert numbers into strings and check for palindrome number in Python.
num = 12321
if str(num) == str(num)[::-1]:
print("It is a palindrome!")
Why it's necessary? This method allows you to apply the same palindrome-checking logic to both strings and numbers, making the solution more versatile and easier to implement.
Edge cases like an empty string or a single character should be considered in your palindrome check, as both are inherently palindromes. Failing to account for these simple cases can lead to unnecessary complications or errors in your program.
Tip: Add checks for strings that are empty or contain only one character.
if len(s) <= 1:
print("It is a palindrome!")
Why it's necessary? Ensuring that edge cases are handled properly makes your palindrome check more robust and reliable across all inputs.
These tips help optimize your code for real-world applications, ensuring it works across diverse use cases and datasets, while keeping your code clean and easy to understand.
Also Read: Essential Python Developer Skills and a Step-by-Step Guide to Becoming a Python Developer
Finding palindrome number in Python is a crucial programming skill, especially in fields like data validation, pattern recognition, and bioinformatics. As industries increasingly rely on data integrity and automation, understanding how to efficiently process palindromes is essential. Professionals skilled in Python and algorithmic thinking are in high demand across software development, machine learning, and biotechnology sectors.
upGrad helps you master such programming concepts through expert-led Python courses. With hands-on projects and real-world applications, you’ll gain the problem-solving skills needed to succeed in today’s competitive tech industry.
In addition to the programs covered in this blog, here are some additional courses that can help you in your learning journey:
If you're unsure where to begin or which area to focus on, upGrad’s expert career counselors can guide you based on your goals. You can also visit a nearby upGrad offline center to explore course options, get hands-on experience, and speak directly with mentors!
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
References:
https://stackoverflow.com/questions/15594895/counting-the-number-of-palindromes-in-a-range-in-python
763 articles published
Rohit Sharma shares insights, skill building advice, and practical tips tailored for professionals aiming to achieve their career goals.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources