How To Check Palindrome Number in Python?

By Rohit Sharma

Updated on Oct 12, 2025 | 10 min read | 16.82K+ 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.

A palindrome number in Python is a number that remains the same when its digits are reversed. Checking for palindrome numbers is a common programming task and a popular coding interview question. Python offers multiple ways to verify palindrome numbers, including string reversal, loops, recursion, and functions. 

In this comprehensive guide, we'll explore everything you need to know about creating a palindrome number program in Python. We will break down three distinct methods, from the most straightforward approach to more advanced techniques. You will learn the logic behind each method, see clear code examples, and understand the pros and cons to help you decide which one is right for your needs. 

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

Method 1: The Easiest Way Using String Slicing 

The most straightforward and "Pythonic" way to check for a palindrome number in Python is by leveraging the power of string slicing. This method is incredibly concise and easy to read, making it a favorite among beginners and professionals alike for its simplicity. 

The core idea is simple: 

  1. Take the number. 
  2. Convert it into a string. 
  3. Reverse the string. 
  4. Compare the original string with the reversed string. 

If they are identical, the number is a palindrome. If not, it isn’t. Python's string slicing makes the reversal step incredibly easy. The syntax [:: -1] can reverse any sequence, including strings. 

The Palindrome Number Code in Python 

Here is the complete palindrome number code in Python using this approach: 

def is_palindrome_slicing(n): 
    """ 
    Checks if a number is a palindrome using string slicing. 
     
    Args: 
        n: An integer. 
         
    Returns: 
        True if the number is a palindrome, False otherwise. 
    """ 
    # Convert the number to a string 
    num_str = str(n) 
     
    # Compare the string with its reverse 
    if num_str == num_str[::-1]: 
        return True 
    else: 
        return False 
 
# --- Example Usage --- 
number_to_check = 12321 
if is_palindrome_slicing(number_to_check): 
    print(f"{number_to_check} is a palindrome number.") 
else: 
    print(f"{number_to_check} is not a palindrome number.") 
 
number_to_check = 12345 
if is_palindrome_slicing(number_to_check): 
    print(f"{number_to_check} is a palindrome number.") 
else: 
    print(f"{number_to_check} is not a palindrome number.") 
  

Step-by-Step Breakdown 

Let's break down how this elegant solution works using the number 121

  1. Function Definition: We define a function is_palindrome_slicing that accepts one argument, n. 
  2. Integer to String Conversion: Inside the function, str(n) converts the integer 121 into the string "121". This is stored in the num_str variable. 
  3. String Reversal: The magic happens with num_str[::-1]. This is Python's extended slice syntax. 
  4. The first colon : means we start from the beginning of the string. 
  5. The second colon : means we go to the end of the string. 
  6. The -1 is the "step," which tells Python to go backward one character at a time. 
  7. This effectively creates a reversed copy of the string. So, "121" reversed is still "121". 
  8. Comparison: The if statement compares the original string num_str ("121") with its reversed version ("121"). Since "121" == "121" is true, the function returns True. 
  9. Output: The example usage code calls the function and prints the appropriate message based on the boolean result. 

Pros and Cons of String Slicing 

This method is fantastic, but it's good to know its trade-offs. 

Pros 

Cons 

Highly Readable: The code is short and easy to understand.  Type Conversion Overhead: Involves converting a number to a string. 
Concise: Often possible to write it in a single line.  Memory Usage: Creates a new, reversed copy of the string in memory. 
Pythonic: Utilizes a feature that is idiomatic to Python.  Less Universal: Logic is specific to languages with easy string slicing. 

For most everyday programming tasks and learning purposes, this is the best method to check for a palindrome number in Python. It's clean, efficient enough, and demonstrates a good understanding of Python's string manipulation capabilities. 

Also Read: Learn the Techniques: How to Reverse a Number in Python Efficiently 

Method 2: The Traditional Approach Using a Mathematical Loop 

While string slicing is fast and easy, sometimes an interviewer might ask you to solve the palindrome problem without converting the number to a string. This tests your understanding of basic arithmetic operations and loops. This method is purely mathematical and relies on reversing the number digit by digit. 

The algorithm for this palindrome number program in Python is as follows: 

  1. Store the original number in a temporary variable so we don't lose it. 
  2. Initialize a new variable, say reversed_num, to 0. 
  3. Use a while loop that continues as long as the original number is greater than 0. 
  4. Inside the loop, extract the last digit of the number using the modulo operator (% 10). 
  5. Add this digit to reversed_num. To do this, multiply reversed_num by 10 first and then add the digit. 
  6. Remove the last digit from the original number using integer division (// 10). 
  7. Once the loop finishes, reversed_num will hold the reversed version of the original number. 
  8. Compare the temporary variable (holding the original number) with reversed_num. 

Data Science Courses to upskill

Explore Data Science Courses for Career Progression

background

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

The Python Code Using a While Loop 

Here is the complete code implementing this mathematical logic: 

def is_palindrome_loop(n): 
    """ 
    Checks if a number is a palindrome using a mathematical loop. 
    This function does not convert the number to a string. 
     
    Args: 
        n: A positive integer. 
         
    Returns: 
        True if the number is a palindrome, False otherwise. 
    """ 
    if n < 0: 
        return False # Negative numbers are not typically considered palindromes 
         
    original_num = n 
    reversed_num = 0 
     
    while n > 0: 
        # Get the last digit 
        digit = n % 10 
         
        # Append the digit to the reversed number 
        reversed_num = (reversed_num * 10) + digit 
         
        # Remove the last digit from the original number 
        n = n // 10 
         
    # Compare the original number with the reversed number 
    return original_num == reversed_num 
 
# --- Example Usage --- 
number_to_check = 121 
if is_palindrome_loop(number_to_check): 
    print(f"{number_to_check} is a palindrome number.") 
else: 
    print(f"{number_to_check} is not a palindrome number.") 
 
number_to_check = 12345 
if is_palindrome_loop(number_to_check): 
    print(f"{number_to_check} is not a palindrome number.") 
  

Dry Run with an Example 

Let's trace the execution with the number 121

  • original_num is set to 121. reversed_num is 0. n is 121. 

    Loop 1

  • n > 0 (121 > 0) is true. 
  • digit = 121 % 10 which is 1. 
  • reversed_num = (0 * 10) + 1 which is 1. 
  • n = 121 // 10 which is 12. 

    Loop 2

  • n > 0 (12 > 0) is true. 
  • digit = 12 % 10 which is 2. 
  • reversed_num = (1 * 10) + 2 which is 12. 
  • n = 12 // 10 which is 1. 

    Loop 3

  • n > 0 (1 > 0) is true. 
  • digit = 1 % 10 which is 1. 
  • reversed_num = (12 * 10) + 1 which is 121. 
  • n = 1 // 10 which is 0. 

    End of Loop

  • n > 0 (0 > 0) is false. The loop terminates. 
  • Final Comparison: The function returns original_num == reversed_num which is 121 == 121, resulting in True. 

Using a For Loop 

You can also adapt this logic for a palindrome number in Python using a for loop. While a while loop feels more natural for this algorithm, a for loop is also possible if you iterate over the digits as characters of a string but perform the mathematical reversal. 

def is_palindrome_for_loop(n): 
    original_num_str = str(n) 
    reversed_num = 0 
     
    for digit_char in original_num_str: 
        digit = int(digit_char) 
        reversed_num = (reversed_num * 10) + digit 
         
    return int(original_num_str) == reversed_num 
  

This hybrid approach uses a for loop for iteration but sticks to the mathematical construction of the reversed number. 

Pros and Cons of the Loop Method 

Pros 

Cons 

No Type Conversion: Operates purely on integers.  More Code: Requires more lines and is less intuitive at first glance. 
Language Agnostic: The core logic can be applied to any language.  Slightly More Complex: The logic involving % and // can be tricky for beginners. 
Good for Interviews: Shows understanding of fundamental algorithms.  Can Overflow: For extremely large numbers in other languages (Python handles large integers). 

This method is an excellent way to demonstrate a deeper understanding of algorithmic thinking when checking for a palindrome number in Python. 

Also Read: Type Casting in Python 

Method 3: An Advanced Technique Using Recursion 

For those looking for a more elegant or advanced solution, recursion offers another way to check for a palindrome number in Python. Recursion is a programming concept where a function calls itself to solve a smaller version of the same problem until it reaches a "base case." 

To check for a palindrome recursively, the logic is: 

  1. Base Case: If the number has one or zero digits, it must be a palindrome. 
  2. Recursive Step: Compare the first and last digits of the number. 
  3. If they are the same, the number might be a palindrome. We then need to recursively call the function on the number without its first and last digits. 
  4. If they are different, the number is definitely not a palindrome. 

Because it is much easier to get the first and last digits from a string, this recursive approach is usually implemented with strings. 

The Recursive Palindrome Code in Python 

Here is what a recursive palindrome number code in Python looks like: 

def is_palindrome_recursive(n): 
    """ 
    Checks if a number is a palindrome using recursion. 
     
    Args: 
        n: An integer. 
         
    Returns: 
        True if the number is a palindrome, False otherwise. 
    """ 
    # Convert the number to a string to work with it recursively 
    s = str(n) 
    return check_recursive(s) 
 
def check_recursive(s): 
    """Helper function for the recursive check.""" 
     
    # Base Case: If the string has 0 or 1 characters, it's a palindrome. 
    if len(s) <= 1: 
        return True 
     
    # Compare the first and last characters. 
    if s[0] == s[-1]: 
        # If they match, check the substring in between. 
        return check_recursive(s[1:-1]) 
    else: 
        # If they don't match, it's not a palindrome. 
        return False 
 
# --- Example Usage --- 
number_to_check = 48984 
if is_palindrome_recursive(number_to_check): 
    print(f"{number_to_check} is a palindrome number.") 
else: 
    print(f"{number_to_check} is not a palindrome number.") 
 
number_to_check = 12345 
if is_palindrome_recursive(number_to_check): 
    print(f"{number_to_check} is a palindrome number.") 
else: 
    print(f"{number_to_check} is not a palindrome number.") 
  

How Recursion Unfolds 

Let's trace check_recursive("48984"): 

       Call 1: check_recursive("48984") 

  • len("48984") is 5, not <= 1. 
  • s[0] ('4') == s[-1] ('4'). This is true. 
  • It returns the result of check_recursive("898"). 

    Call 2: check_recursive("898") 

  • len("898") is 3, not <= 1. 
  • s[0] ('8') == s[-1] ('8'). This is true. 
  • It returns the result of check_recursive("9"). 

    Call 3: check_recursive("9") 

  • len("9") is 1. This is the base case
  • It returns True. 

    Unwinding

  • The True value is passed back to Call 2. 
  • Call 2 returns True to Call 1. 
  • Call 1 returns True to the original is_palindrome_recursive function. 

The final result is True, correctly identifying 48984 as a palindrome. This approach elegantly breaks the problem down into smaller, identical subproblems. 

Pros and Cons of Recursion 

Pros 

Cons 

Elegant Solution: The code can be very clean and reflect the problem's nature.  Less Intuitive: Can be difficult for beginners to understand and debug. 
Declarative: Focuses on what to do, not how to do it (like a loop).  Performance Overhead: Function calls can be slower than iteration. 
Good for Certain Problems: Ideal for problems that have a recursive structure.  Stack Overflow Risk: For very large numbers (long strings), you can exceed the maximum recursion depth. 

Using recursion for checking a palindrome number in Python is a great way to practice an important computer science concept, even if it's not always the most practical solution for this specific problem compared to slicing or a simple loop. 

Also Read: Recursion in Data Structures: Types, Algorithms, and Applications 

What Exactly is a Palindrome Number? 

After exploring  the code, let's make sure we're on the same page. A palindrome is a sequence that reads the same backward as it does forward. This concept applies to words ("madam," "racecar"), phrases, and, for our purpose, numbers. 

A palindrome number is a number that remains the same when its digits are reversed. 

  • For example, 121 is a palindrome because if you reverse the digits, you still get 121. 
  • Similarly, 88 is a palindrome. 
  • A more complex example is 9009

On the other hand, a number like 123 is not a palindrome because its reverse is 321, which is not the same as the original. The core idea is symmetry. The sequence of digits is perfectly mirrored around its center. 

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

Understanding this concept is the first step toward writing a program to identify them. Here’s a quick table to make it even clearer: 

Original Number 

Reversed Digits 

Is it a Palindrome? 

121  121  Yes 
345  543  No 
55  55  Yes 
48984  48984  Yes 
10  01 (or 1)  No 

This simple check is a fantastic exercise for learning fundamental programming concepts like: 

  • Loops: Iterating through the digits of a number. 
  • String Manipulation: Converting numbers to strings to use powerful built-in methods. 
  • Mathematical Operations: Using arithmetic to reverse a number without any conversions. 
  • Conditional Logic: Using if-else statements to determine and state the result. 

Whether you are preparing for a coding interview or just sharpening your Python skills, mastering the logic for checking a palindrome number in Python is an invaluable skill. It demonstrates your ability to break down a problem into logical steps and implement a solution efficiently. 

Comparing the Methods: Which Palindrome Check is Best? 

We've explored three different ways to check for a palindrome number in Python. Each has its own strengths and weaknesses, and the "best" method often depends on the context, such as readability, performance requirements, or interview constraints. 

Let's summarize our findings in a comparison table to help you choose the right approach for your situation. 

Feature 

Method 1: String Slicing 

Method 2: Mathematical Loop 

Method 3: Recursion 

Ease of Use  Very Easy. Ideal for beginners.  Moderate. Requires understanding of arithmetic operators.  Difficult. Requires understanding of recursion. 
Code Length  Very Short. Can be a one-liner.  Moderate. More verbose than slicing.  Moderate. Involves a helper function. 
Performance  Generally Fast. Highly optimized in CPython.  Very Fast. Avoids string conversion overhead.  Slower. Function call overhead can be significant. 
Readability  Excellent. The intent is very clear.  Good. The algorithm is straightforward once understood.  Moderate. Can be hard to follow for the untrained eye. 
Best Use Case  General purpose, quick scripts, learning Python syntax.  Technical interviews, language-agnostic logic tests, performance-critical code.  Academic purposes, practicing recursion, problems with inherent recursive structures. 

Final Recommendation 

  • For Beginners and Everyday Code: Stick with Method 1: String Slicing. It is the most Pythonic, readable, and is perfectly efficient for almost any real-world scenario. It's the solution you should reach for first. 
  • For Technical Interviews: Be prepared to use Method 2: The Mathematical Loop. Interviewers often add the constraint "without converting to a string" to test your problem-solving skills with basic arithmetic and loops. Knowing this method shows depth. 
  • For Demonstrating Advanced Knowledge: Use Method 3: Recursion if you want to showcase your understanding of more advanced computer science concepts. While not the most practical for this specific task, it’s a powerful tool to have in your arsenal. 

Ultimately, understanding all three methods for creating a palindrome number program in Python will make you a more well-rounded and versatile programmer. 

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!

Frequently Asked Questions (FAQs)

1. What is a palindrome number?

A palindrome number is a number that reads the same forwards and backward. For example, 121, 343, and 9009 are palindrome numbers because their digit sequences are symmetrical. 

2. Is 0 a palindrome number?

Yes, 0 is considered a palindrome number. It's a single-digit number, and all single-digit numbers read the same forwards and backward, so they are palindromic by definition. 

3. Are negative numbers like -121 palindromes?

Generally, negative numbers are not considered palindromes. The negative sign at the beginning breaks the symmetry; when reversed, -121 would become 121-, which is not a number. Most palindrome checks handle negative numbers as non-palindromes. 

4. How can I check for a palindrome string in Python?

Checking for a palindrome string is even simpler than for a number. You can directly use the string slicing method: my_string == my_string[::-1]. This expression will evaluate to True if the string is a palindrome. 

5. Which method for checking palindrome numbers is the fastest in Python?

For most practical inputs, the performance difference is negligible. However, the mathematical loop method is often slightly faster as it avoids the overhead of converting an integer to a string object and then creating a second, reversed string object. 

6. Can I check for a palindrome number without converting it to a string?

 Yes, you can. The mathematical loop method (Method 2 in this blog) is designed specifically for this purpose. It uses arithmetic operators like modulo (%) and integer division (//) to reverse the number mathematically. 

7. What is the [::-1] syntax in Python?

This is Python's extended slice syntax. [start:stop:step] allows you to take a portion of a sequence. When you use [::-1], you are telling Python to start from the beginning, go to the end, and move backward one step at a time, which effectively reverses the sequence. 

8. Why is the modulo operator (%) used in the loop method?

The modulo operator (n % 10) is used to get the remainder of a division. When you divide a number by 10, the remainder is always the last digit. This is a clever way to extract digits from a number one by one, from right to left. 

9. What is the difference between / and // in Python?

In Python 3, / performs float division (e.g., 121 / 10 is 12.1), while // performs integer (or "floor") division. Integer division discards the decimal part (e.g., 121 // 10 is 12), which is useful for removing the last digit from a number. 

10. What is recursion in Python?

Recursion is a programming technique where a function calls itself to solve a problem. The function breaks the problem down into smaller, identical subproblems until it reaches a simple "base case" that can be solved directly without further recursion. 

11. Is the recursive method for palindrome checking efficient?

 The recursive method is generally less efficient than iterative solutions (like loops) for this problem. Each recursive call adds a new layer to the system's call stack, which consumes memory and can be slower than a simple loop. 

12. How can I write a one-line palindrome check in Python?

 You can write a very concise one-line function using a lambda function and string slicing: is_palindrome = lambda n: str(n) == str(n)[::-1]. Then you can call it like is_palindrome(121). 

13. Can I use a for loop to check for a palindrome number?

 Yes, you can. A common way is to convert the number to a string and then use a for loop to compare characters from the beginning and end, moving inwards. Alternatively, you can iterate through the string's digits to mathematically construct the reversed number. 

14. How to handle floating-point numbers when checking for palindromes?

Floating-point numbers (like 12.21) are typically not checked for palindromes because the decimal point breaks the symmetry. If you needed to, you would first have to define rules, such as ignoring the decimal point and checking if 1221 is a palindrome. 

15. What are some common mistakes when writing a palindrome program?

A common mistake in the loop method is forgetting to store the original number in a separate variable before the loop starts. The loop modifies the number, so you need the original value for the final comparison. Another is mixing up / and // division. 

16. How does this palindrome logic apply to other data types?

The core logic of comparing a sequence to its reverse applies to any ordered data type. For example, you can check if a list or tuple is a palindrome using the same slicing technique: my_list == my_list[::-1]. 

17. Where can I practice more Python problems like this?

Websites like LeetCode, HackerRank, Codewars, and GeeksforGeeks are excellent platforms for practicing a wide range of programming problems, from beginner to advanced levels, including many variations of the palindrome problem. 

18. What is the time complexity of the string slicing method?

The time complexity is roughly O(N), where N is the number of digits in the number. This is because converting the number to a string takes O(N) time, reversing it takes O(N), and comparing also takes O(N). 

19. What is the space complexity of the mathematical loop method?

The space complexity is O(1), or constant space. This is because you are only using a few variables to store numbers (original_num, reversed_num, digit), and the amount of memory used does not increase with the size of the input number. 

20. Can this logic be used in other programming languages?

Absolutely. The mathematical loop method is a universal algorithm that can be implemented in almost any programming language, like C++, Java, or JavaScript, using their respective arithmetic operators. The string slicing method's ease of implementation may vary depending on the language's built-in string functionalities. 

Rohit Sharma

834 articles published

Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...

Speak with Data Science Expert

+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

upGrad
new course

Certification

30 Weeks

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree

17 Months