Check Palindrome Number in Python

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digits

What You’ll Learn

A palindrome number reads the same forwards and backwards — like 121 or 7. This tutorial covers reversing digits with % 10 and // 10, listing palindromes in a range, a string alternative, a live checker, worked Python examples, edge cases, and complexity.

Definition

Same both ways

Digits match left-to-right and right-to-left.

Reverse

% 10 / // 10

Build the digit reverse, then compare.

Save Original

Before the loop

Keep a copy before you destroy n.

Range List

100..200

Reuse the helper for each candidate.

Live Preview

Try 121 / 123

Check any nonnegative integer live.

O(d) Cost

d = digits

One pass over the digits of n.

Introduction

A palindrome number looks the same when its digits are reversed. The classic interview approach builds that reverse with a loop, then compares it to the original.

Single-digit values always pass. Numbers ending in 0 (except 0 itself) fail because leading zeros disappear in the reversed integer. This page focuses on nonnegative integers for beginner clarity.

Why it matters?

It is a classic while-loop drill that combines remainder, integer division, and careful state saving.

Key Highlights

Reverse Loop

rev = rev*10 + n%10.

Compare

original == reversed.

Trailing Zeros

120 reverses to 21.

Single Digit

Always a palindrome.

In short: save the original, reverse digits in a loop, return whether they match.

📝 Problem & Approach

Given a nonnegative integer, decide whether its decimal digits form a palindrome, and optionally list all palindromes in a range.

python
# 121 -> reverse 121 -> palindrome
# 123 -> reverse 321 -> not
# 120 -> reverse 21  -> not

Inputs & Outputs

ItemTypeDescription
number / nintNonnegative integer to test.
ReturnboolTrue when original equals digit reverse.
Range printtextPalindrome values from start through end.

Minimal workflow

Pseudocode
function is_palindrome(n):
    original = n
    reversed = 0
    while n != 0:
        reversed = reversed * 10 + (n mod 10)
        n = floor(n / 10)
    return original == reversed

Method comparison

MethodIdeaNotes
Arithmetic reverseLoop with % / //Interview default
String slicestr(n) == str(n)[::-1]Short; mention after arithmetic
Two pointers on digitsCompare endsUseful for digit arrays

⚡ Quick Reference

GoalPattern
Last digitdigit = n % 10
Append to reverserev = rev * 10 + digit
Drop last digitn //= 10
Comparereturn original == rev
String checkstr(n) == str(n)[::-1]
Inclusive rangerange(100, 201)

📋 Arithmetic vs String vs Pointers

Same yes/no answer — different interview signals.

Arithmetic
rev*10 + n%10

This page — classic interview style

String
s == s[::-1]

Short Python; show loops first

Two pointers
left / right

Natural for digit lists

Interview tip
save original

Copy n before the reverse loop

Context

When This Problem Shows Up

Reach for a digit-reverse palindrome check whenever symmetry of digits matters.

  1. Interview classics

    While loops, remainder, and comparison.

  2. Digit drills

    Practice % 10 and // 10 together.

  3. Filtering ranges

    List all palindromes in an interval.

  4. Bridge to string pals

    Same idea as word palindromes.

  5. Not signed by default

    Define negative behavior separately.

Key benefit: one reusable helper that teaches digit peeling, state saving, and symmetry checks.

🔮 Live Preview

Enter a nonnegative integer and check whether it is a palindrome.

Try 121, 123, 0, or 7.

Live result
Press “Check palindrome”.

Examples Gallery

Three complete Python programs — arithmetic check for 121, palindromes from 100 to 200, and a string-based alternative. Click View Output to reveal sample console results.

📚 Getting Started

Arithmetic reversal and a single sample value.

Example 1 — Check One Number

Use arithmetic reversal and compare with the original.

python
def is_palindrome(number: int) -> bool:
    original_number = number
    reversed_number = 0

    while number != 0:
        remainder = number % 10
        reversed_number = reversed_number * 10 + remainder
        number //= 10

    return original_number == reversed_number


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

How It Works

The loop peels digits from the right and builds reversed_number. For 121 the reverse is also 121, so the helper returns True.

⚡ Listing Palindromes

Reuse the same helper inside an inclusive range loop.

Example 2 — Palindromes from 100 to 200

Scan each candidate and print those that pass the check.

python
def is_palindrome(num: int) -> bool:
    original_num = num
    reversed_num = 0

    while num != 0:
        remainder = num % 10
        reversed_num = reversed_num * 10 + remainder
        num //= 10

    return original_num == reversed_num


print("Palindrome numbers in the range 100 to 200:")
for i in range(100, 201):
    if is_palindrome(i):
        print(i, end=" ")

How It Works

Python range excludes the end, so use 201 to include 200. Three-digit palindromes in this band look like 1a1.

Example 3 — String Alternative

Compare the digit string with its reverse slice — short, but show arithmetic first in interviews.

python
def is_palindrome_str(number: int) -> bool:
    s = str(number)
    return s == s[::-1]


for n in (121, 123, 7, 120):
    label = "palindrome" if is_palindrome_str(n) else "not a palindrome"
    print(f"{n} is {label}.")

How It Works

s[::-1] reverses the characters of the digit string. Leading zeros never appear in str(n), so 120 still fails — matching the arithmetic rule.

🧠 How Digit Reversal Works

1

Save original

Copy n before the loop mutates it.

Setup
2

Peel last digit

digit = n % 10, then n //= 10.

Loop
3

Build reverse

rev = rev * 10 + digit each step.

Build
=

Compare

Palindrome if original == rev.

🔎 Worked Walkthrough — 121

Trace the reverse loop for n = 121.

Stepndigitrev
Start1210
11211
21212
301121

original 121 equals rev 121 — palindrome.

Use Cases

Where palindrome-number checks show up beyond the interview prompt.

1. Interview Classics

While loops and digit math.

Example: write is_palindrome.

2. Range Filters

List pals in an interval.

Example: 100..200.

3. Digit Drills

Practice % 10 and // 10.

Example: reverse any n.

4. Edge-Case Talk

Trailing zeros and single digits.

Example: 120 vs 7.

5. String Twin

Same idea as word palindromes.

Example: radar / level.

6. Next: Pascal

Continue the interview track.

Example: related CTA.

Pro Tip: say “save original, reverse with % and //, compare” before typing code.

Advantages

Why the arithmetic reverse approach works well in interviews.

  1. 1. Easy to Trace

    Dry-run 121 on paper and watch rev grow.

  2. 2. No String Required

    Shows comfort with integer arithmetic.

  3. 3. Reusable Helper

    Same function powers single checks and ranges.

  4. 4. Python-Friendly

    No overflow worries with Python ints.

Pro Tip: lead with arithmetic reverse; offer the string slice as a concise alternative.

Usage Tips

Small habits that keep palindrome checks interview-ready.

  1. 1. Save Original First

    Copy n before the reverse loop.

  2. 2. Mention Trailing Zeros

    Call out 120 → 21 as a classic trap.

  3. 3. Define Negatives

    State whether negatives are allowed.

  4. 4. Inclusive Ranges

    Use end + 1 with Python range.

  5. 5. Offer String Later

    Show arithmetic first, then s[::-1].

Pro Tip: dry-run 121 and 120 aloud — if both match the table, your reverse logic is solid.

Common Pitfalls

Mistakes that commonly break palindrome-number programs.

  1. 1. Forgetting to Save Original

    Comparing after n is already zeroed out.

    → Copy original before the loop.

  2. 2. Trailing Zero Blind Spot

    Thinking 120 should match 021.

    → Integer reverse drops leading zeros.

  3. 3. Off-by-One Range

    Missing the last value with exclusive end.

    → Use range(start, end + 1).

  4. 4. Silent Negatives

    Undefined behavior for -121.

    → Reject or define a signed policy.

  5. 5. Only Showing Strings

    Skipping the arithmetic method in interviews.

    → Lead with the reverse loop.

Edge Cases

Handle these before claiming the check is complete.

Zeros

Trailing zeros

120 reverses to 21, so it is not a palindrome.

Single

n < 10

Always a palindrome for nonnegative numbers.

Zero

n = 0

Zero is a palindrome.

Neg

Negative input

This page rejects negatives in live preview for clarity.

Even len

Even digit counts

Works the same — e.g. 1221.

Large

Many digits

Still O(d); Python ints grow as needed.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Single digits. Every n in 0..9 is a palindrome.
  • Form 1a1. Three-digit pals look like first digit equals last.
  • Words too. The same symmetry idea applies to strings like radar.
  • No Python overflow. Reversed values can grow freely unlike fixed-width ints.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Trace 121

  • Reproduce the walkthrough table
  • Confirm original == rev

2. Reject 120

  • Show reverse becomes 21
  • Explain leading zeros

3. List 100..200

  • Reproduce Example 2
  • Expect ten three-digit pals

4. String twin

  • Implement Example 3
  • Match arithmetic answers

Notes

  • Core trick: reverse digits and compare with original.
  • Range scan: reuse the same helper for each candidate.
  • Watch-outs: trailing zeros and negative input rules.
  • Python integers do not overflow like fixed-width ints. A string comparison also works, but arithmetic reverse is the classic interview approach.

Quick Takeaway: save original, reverse with % and //, return original == rev.

⏱️ Time and Space Complexity

OperationTimeExtra space
is_palindrome(n)O(d)O(1)
Range [a, b]O((b-a+1) * d)O(1)
String slice checkO(d)O(d) for the string

Here d is the number of decimal digits in the value being tested.

Wrap Up

🎉 Conclusion

Checking a palindrome number means reversing its digits and comparing with the original. Save a copy first, peel digits with % 10 and // 10, and watch for trailing zeros.

Practice the three examples above, then continue to generating Pascal’s triangle.

original == reverse(digits) — that is the whole check.

💡 Best Practices

✅ Do

  • Save original before reversing
  • Use % 10 and // 10
  • Call out trailing zeros
  • Reuse the helper in ranges
  • State nonnegative scope

❌ Don’t

  • Compare after destroying n
  • Treat 120 as a palindrome
  • Ignore exclusive range ends
  • Leave negatives undefined
  • Skip arithmetic in interviews

Key Takeaways

Knowledge Unlocked

Five things to remember about palindrome numbers

Check digit symmetry the interview-friendly way.

5
Core concepts
= 02

Compare

original == rev

Rule
0 03

Zeros

120 ≠ 21

Edge
1 04

Digits

0..9 always yes

Base
O 05

Cost

O(d) / O(1)

Analysis

❓ Frequently Asked Questions

A palindrome number reads the same from left to right and right to left, like 121 or 9009.
Reversing digits gives a value you can directly compare with the original using ==.
Yes. Any single-digit number is palindrome.
Yes. Zero reads the same in both directions.
This lesson uses nonnegative integers. You can define separate behavior for negatives if required.
Checking one number is O(d) where d is digit count. Range scan multiplies this by number of tested values.
Its digit reverse is 021, which as an integer is 21 — not equal to 120.
Yes: str(n) == str(n)[::-1]. Interviews often want the arithmetic reverse first.
No. Python integers grow as needed, unlike fixed-width ints in some languages.

Did you Know? 🔊

The word palindrome also describes words like “radar” or “level”. For integers, we compare digits only, so single-digit values like 7 always pass.

Continue to Pascal’s Triangle

Learn how to generate Pascal’s triangle rows with nested loops in Python.

Pascal’s triangle tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful