Python Program to Check if a String is Palindrome or Not

Last Updated : 18 May, 2026

Given a string and the task is to check whether it is a palindrome. A palindrome is a string that reads the same forward and backward. For example:

Input: "madam"
Output: Palindrome

Input: "hello"
Output: Not a Palindrome

Let's explore different methods to check if a string is a palindrome.

Using Two Pointer Technique

This method compares characters from both ends moving toward the center. It is most efficient because it checks only half of the string without creating extra copies.

Python
s = "malayalam"  
i, j = 0, len(s) - 1  
is_palindrome = True  

while i < j:
    if s[i] != s[j]:  
        is_palindrome = False
        break
    i += 1
    j -= 1

if is_palindrome:
    print("Yes") 
else:
    print("No")   

Output
Yes

Explanation:

  • while loop compares characters from both ends towards the center as long as i < j .
  • if no mismatch is found, the pointers move inward for the next comparison
  • After the loop, it prints "Yes" if is_palindrome is True, otherwise "No".

Using all() with Generator Expression

This method checks if all mirrored characters are equal using a generator expression. The string is a palindrome if all comparisons pass.

Python
s = "malayalam"

if all(s[i] == s[- i- 1] for i in range(len(s) // 2)):
    print("Yes")
else:
    print("No")

Output
Yes

Explanation:

  • range(len(s)//2) generates indices for the first half of the string and s[-i-1] accesses characters from the end of the string.
  • s[i] == s[-i-1] checks equality for mirrored positions and all() returns True only if every comparison is True.

Using Slicing

This method reverses the string using slicing (s[::-1]) and compares it with the original string. If both match, the string is a palindrome.

Python
s = "malayalam" 

if s == s[::-1]:
    print("Yes")
else:
    print("No")

Output
Yes

Explanation: It compares the string 's' with its reverse s[::-1]. If they are equal, it prints "Yes" otherwise, it prints "No".

Using reversed() + join()

This method creates a reversed version of the string using reversed() and join(), then compares it with the original string. If they match, it is a palindrome.

Python
s = "geeks"
rev = ''.join(reversed(s))

if s == rev:
    print("Yes")
else:
    print("No")

Output
No

Explanation: creates a reversed version of the string with ''.join(reversed(s)) and compares it with the original string. If they are equal, it prints "Yes" otherwise, it prints "No".

Comment