View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How To Check Palindrome Number in Python?

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.

Want to learn how to check for palindrome number in Python and enhance your programming skills? With upGrad’s Online Software Development Courses, you'll gain practical experience in Python and problem-solving techniques, preparing you for success in the tech industry.

How to Check Palindrome Number in Python? Step-by-Step Process

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.

Method 1: Reverse the Number and Compare (Naïve Approach)

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:

  • Input the number: Take the input from the user.
  • Reverse the number: Extract each digit of the number and reverse it.
  • Compare the original and reversed number: If they are equal, it’s a palindrome.

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:

  • The code works by extracting digits from the number using the modulus operator (%) and constructing a reversed number.
  • The loop runs until the number becomes zero.
  • Finally, it compares the original number with the reversed number to determine if they are equal.

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.

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

You can begin your Python learning journey with upGrad’s free PythonProgramming with Python: Introduction for Beginners course. Learn core programming concepts such as control statements, data structures, like lists, tuples, and dictionaries, and object-oriented programming.

Also Read: Python Cheat Sheet: From Fundamentals to Advanced Concepts for 2025

Method 2: Using String Slicing (One-Liner Approach)

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:

  • Input the string or number: Accept the input as a string.
  • Reverse the string: Use slicing to reverse the string.
  • Compare the original and reversed string: If they are the same, it’s a palindrome.

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:

  • The slicing operation [::-1] reverses the string.
  • The if statement checks if the original string is equal to its reversed version.
  • This method works for both numeric and string inputs, making it flexible and simple.

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

Method 3: Using Recursion

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:

  • Check the base case: If the string has only one or zero characters, it’s automatically a palindrome.
  • Compare the first and last characters: If they are equal, recursively check the next pair.
  • Recursively reduce the string: Move inwards until all pairs are compared.

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:

  • The function isPalindrome checks if the string is a palindrome by comparing the first and last characters recursively.
  • If the characters match, it calls itself with the next pair of characters, moving inward.
  • The base case terminates the recursion when the start index is greater than or equal to the end index.

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.

If you want to build a higher-level understanding of Python, upGrad’s Learn Basic Python Programming course is what you need. You will master fundamentals with real-world applications & hands-on exercises. Ideal for beginners, this Python course also offers a certification upon completion.

Also Read: Career Opportunities in Python: Complete Guide for 2025

Method 4: Using the reversed() Function

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:

  • Input the string: Accept the string input.
  • Reverse the string: Use the reversed() function to reverse the string.
  • Compare the original and reversed string: If they match, it’s a palindrome.

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:

  • The reversed() function returns an iterator, which is then converted to a string using ''.join().
  • The original string is compared to the reversed string to determine if it's a palindrome.

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

Method 5: Using a For Loop (Manual Check)

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:

  • Input the string: Accept the string as input.
  • Loop through the string: Compare characters from the start and end.
  • Check for mismatch: If any pair of characters don’t match, return False.

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:

  • This method removes spaces and converts the string to lowercase to ensure the comparison is case-insensitive.
  • It uses a for loop to manually build the reversed string and then compares it to the original string.

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.

Important Tips to Keep in Mind When Checking Palindrome Number in Python

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:

1. Handle Case Sensitivity

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").

2. Remove Non-Alphanumeric Characters

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).

3. Optimize for Large Strings

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.

4. Consider Using Recursion for Practice

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.

5. Efficient Comparison of Numbers

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.

6. Be Mindful of Edge Cases

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

How Can upGrad Help You Learn Python Programming?

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

Frequently Asked Questions (FAQs)

1. How do I efficiently check a palindrome number in Python for large strings?

2. What’s the difference between using string slicing and recursion for palindrome checks?

3. How do I handle spaces and punctuation when checking for a palindrome in a sentence?

4. Is it possible to check for palindrome numbers without converting them to strings?

5. What are some common performance issues when checking for palindrome number in Python?

6. How do I compare strings case-insensitively when checking for palindrome number in Python?

7. Can palindromes be checked using built-in Python functions like reversed()?

8. What happens if I try to check an empty string or a single character as a palindrome?

9. Is it efficient to use recursion for palindrome checking in Python?

10. How do I optimize palindrome checking for very large strings in Python?

11. How can I check if a string is a palindrome and ignore extra spaces?

Rohit Sharma

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

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

17 Months

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months