Palindrome Function in Python
  1. What is Palindrome
  2. What is a Palindrome Number
  3. What is a Palindrome String
  4. What is a Palindrome Phrase
  5. Palindrome Examples
  6. Palindrome in Python Algorithm
  7. Palindrome in Python Code
    a. using while loop
    b. Using reverse Function
  8. Check if a Linked List is a Palindrome

What is Palindrome?

Happy belated multi-cultural palindrome day! 02/02/2020 was a unique day in February. It works whether your preferred date format is MM/DD/YYYY or DD/MM/YYYY or YYYY/MM/DD.

Palindrome example

These patterns are called palindromes. Reading them from the first character or reading them backwards doesn’t make any difference. This is an interesting introductory problem to solve with the use of programming. In this blog, we will understand the thought process and go step by step and come up with various solutions to check if the string is a palindrome or not.

Palindrome is defined as a word, phrase, number,or other sequence of characters which reads the same backward as forward. They are classified into 3 types,which are Palindrome numbers,
Palindrome strings, Palindrome phrase: A collection of words and special characters

What is a Palindrome Number?

A Palindrome Number is a collection of numbers which remains the exact same way when read backwards. These numbers are also said to be symmetrical. When its digits are reversed, they turn out to be the exact same number as the original number. For eg : 1234321 is a Palindrome. It its digits are reversed, it again becomes 1234321 which was our original number. 1234232 is not a Palindrome. When reversed, the new number becomes 2324321 which is not the same as the original number.

What is a Palindrome String?

A Palindrome String is a collection of alphabets which remains the exact same way when read backwards. They are also called Symmetrical Alphabets. When its alphabets are written in reverse order, they turn out to be the exact same combination of alphabets as the original string. For eg : “madam” is a Palindrome. It its alphabets are reversed, it again becomes “madam” which was our original string. “napkin” is not a Palindrome. When reversed, the new number becomes “nikpan” which is different from the original string.

What is a Palindrome Phrase?

Palindrome Phrase is a collection of words and special characters, which remains the exact same way when read backwards. These phrases are also said to be symmetrical. When the phrase is reversed, they turn out to be the exact same phrase as the original phrase. For eg : a1b2c33c2b1a is a Palindrome. It the phrase is reversed, it again becomes a1b2c33c2b1a which was our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.

Palindrome Examples

Below are a few examples of Palindromes

  • Mom
  • Madam
  • a2332a
  • Rubber
  • Dad
  • 123454321

Trivia: Is 02/02/2020 a palindrome string when considered as a palindrome phrase?

We will look at the logical steps of building a solution for checking strings that have the palindrome property.

Palindrome in Python Algorithm

You can go through and enroll in these Python related courses to get the comfortable in Python Programming Language and get your free certificate on Great Learning Academy, before practicing Palindromes algorithm and code in Python.

Data Science with Python
Machine Learning with Python
Deep Learning with Python
Artificial Intelligence with Python

Now how to create Palindromes in Python?

Consider the algorithm for the Problem Statement: Find if a string is Palindrome or not

  1. Check if the index first and index last letters are the same; if not same return false
  2. Repeat step 2 by incrementing the first index and decrementing the last index
  3. Repeat step 3 while first < last If( first > last) then return True

Now let us consider an algorithm for the Problem Statement: Find if a number is a Palindrome or not.

  1. Copy the input number in another variable so that we can compare them later.
  2. Next, we reverse the given number. To reverse the number follow these steps:
    1. Isolate the last digit of a number. The modulo operator (%) returns the remainder of a division
    2. Append lastDigit to reverse. reverse = (reverse * 10) + lastDigit.
    3. Remove last digit from number. number = number / 10.
    4. Iterate this process. while (number > 0)
  3. Now we compare the reversed number with the original number.
  4. If the numbers are the same, then the number is a palindrome ,else it is not

Now that we have the algorithm let us convert it into code by following the similar logic.

Palindrome in Python Code

Using While Loop (number)

number=int(input("Enter any number :"))
#store a copy of this number
#calculate reverse of this number
    #extract last digit of this number
    #append this digit in reveresed number
    #floor divide the number leave out the last digit from number
#compare reverse to original number
    print("The number is palindrome!")
    print("Not a palindrome!")

Using While Loop (string)

def check_palindrome(string):
    length = len(string)
    first = 0
    last = length -1 
    status = 1
               status = 0
    return int(status)  
string = input("Enter the string: ")
print("Method 1")
status= check_palindrome(string)
    print("It is a palindrome ")
    print("Sorry! Try again")


Input – Madam
Output – It is a palindrome

This is a good approach, but python also enables us to use the reverse function. We know intuitively that a word read forwards and backwards, if same is a palindrome. Hence, let us generate the forward and backward string for the same, and check if the two strings are the same.

Using Reverse Function

def check_palindrome_1(string):
    reversed_string = string[::-1]
    return status

string = input("Enter the string: ")
status= check_palindrome_1(string)
    print("It is a palindrome ")
    print("Sorry! Try again")


Input : Enter the string: malayalam
Output : It is a palindrome

Palindrome in a Linked List

Let’s step this up and consider another data structure. What if the data is stored in a linked list? To tackle this, we need to understand linked lists. Linked list is a data structure that has a non contiguous allocation of memory.

We will begin by defining a linked list in python.

class ListNode:
    def __init__(self, x):
        self.val = x = None
class Solution:
    def __init__(self,seq):
        """prepends item of lists into linked list"""
        self.head = None
        for item in seq:
            node = ListNode(item)
   = self.head
            self.head = node

    def palindrome(self):
        """ Check if linked list is palindrome and return True/False."""
        node = self.head
        var = node #var is initialized to head
        prev = None #initially, prev is None
        # prev approaches to middle of list till var reaches end or None 
        while var and
            var =
            temp =   #reverse elements of first half of list
   = prev
            prev = node
            node = temp
        if var:  # in case of odd num elements
            tail =
        else:    # in case of even num elements
            tail = node
        while prev:
            # compare reverse element and next half elements          
            if prev.val == tail.val:
                tail =
                prev =
                return False
        return True
# Test Cases
list_1 = Solution([7, 8, 6 ,  3 , 7 ,3 , 6, 8, 7])
print([7, 8, 6 ,  3 , 7 ,3 , 6, 8, 7],end='->')
list_2 = Solution([6 , 3 , 4, 6])
print([6 , 3 , 4, 6],end='->')
list_3 = Solution([3, 7 ,3 ])
print([ 3 , 7, 3],end='->')
list_4 = Solution([1])
print( list_4.palindrome())


Output –
3, 7, 3 – True
1 – True

The logic for checking if a linked list is a palindrome or not is the modified version of the one we implemented on strings and arrays. We check if the reverse of the linked list is same as the original sequence. Instead of reversing the entire linked list, and storing it in a temporary location, we reverse the first half of the linked list, and check if the first half and second half match after reversal.

Check out the a* Algorithm in Artificial Intelligence

Therefore, we define a function called palindrome, which has parameters node, var( stands for variable), previous and temp. We jump till the end of the list using the variable var in line 29, and meanwhile we store the previous node data in variable prev. Therefore, comparing the prev.val and tail.val in line 41 gives us the answer.

# Test Cases
list_1 = Solution([7, 8, 6 ,  3 , 7 ,3 , 6, 8, 7])
list_2 = Solution([6 , 3 , 4, 6])
list_3 = Solution([3, 7 ,3 ])
listl_4 = Solution([1])
Print( list_4.palindrome())

In this article, we looked at palindromes inside out and understood them thoroughly. Try coming up with better implementation techniques using different data structures to improve your command over coding. We shall keep posting many more articles on implementing data structures and algorithms using Python. Stay tuned.

Check out our Python Guide to learn Python yourself

Learn how to find the Factorial of a Number in Python

Learn to print the Fibonacci series in Python

Explore all the free courses at Great Learning Academy, get the certificates for free and learn in demand skills. 



Please enter your comment!
Please enter your name here

18 − two =