Home

 › 

Articles

 › 

Understanding Palindrome In Python, With Examples

Palindrome in Python

Understanding Palindrome In Python, With Examples

Key Points

  • Palindromes are sequences that read the same backward as they do forwards, and can contain numbers, letters, or special characters.
  • Palindromes have practical applications in programming, data encryption, and coding competitions.
  • Python offers three main methods for checking palindromes: while loops, recursion, and built-in functions like string slicing and reversed().
  • The time and space complexity of palindrome operations depend on the method used, with while loops generally having O(n) time complexity and O(1) space complexity.
  • Recursion can be optimized by stopping early if a false condition is reached, and memoization can be used to avoid repeating identical operations.

“Palindrome” might sound like a complicated concept, but it’s a lot simpler than it sounds. They’re often used in programming, especially in Python, as part of the problem-solving process. There are various methods provided by Python for working with palindromes and checking for them. We’re going to get into these today, how they’re checked, and how they’re used.

What is a Palindrome?

In simple terms, a palindrome is a sequence that’s the same backward as it is forwards. They can contain numbers, letters, or special characters. For example, consider the sequence ‘54245”, or the word “racecar”. Although one contains numbers and the other letters, we can see that the sequence is identical when read backward. Therefore, these are palindromes or can be described as having palindromic behavior.

What Are the Uses of Palindromes?

Many coding projects make use of palindromes, whether we’re checking for the symmetry of a string, want to find the longest palindromic sequence, or manipulate palindromes to solve a more complex problem. They’re often used in data encryption as well as in optimizing code since they can reduce the number of operations required. As well as these, palindromes often feature in coding competitions and interviews. As such, knowing how they work is a useful technique to have in your programming toolbelt.

The Algorithm for Checking a Palindrome in Python

The process for checking whether a sequence is palindromic is rather simple and similar to how we would do it ourselves. First, the sequence is read character by character, with each being held in a temporary variable. After this, the sequence is reversed, and each character is compared with the stored character. If all are the same, we usually verify this by printing a message. Likewise, if the sequence is determined to not be palindromic, this is printed to the console.

How Are Palindromes Checked in Python?

Generally, there are three ways to perform a palindrome check in Python -while loops, recursion, or the built-in functions. Let’s explore each of these briefly.

While loops

The way these work is fairly simple. As mentioned before, each character is stored in a temporary variable, the sequence is then reversed using a while loop and compared with the original input. For example, take a look at this code:

def is_palindrome(word):
    word = word.replace(" ", "").lower()

    start = 0
    end = len(word) - 1

    while start < end:
        if word[start] != word[end]:
            return False

        start += 1
        end -= 1

    return True

input_word = input("Enter a word or phrase: ")
if is_palindrome(input_word):
    print(f"{input_word} is a palindrome.")
else:
    print(f"{input_word} is not a palindrome.")

Here, we use the “is_palindrome” method to determine whether the sequence is palindromic. We receive a message on the console showing this. The while loop uses pointers to the start and end characters, and the corresponding positions are compared. These are incremented until they cross each other, at which point they stop. In this case, we were asked to enter a sequence. “STEPPETS” was entered, and determined to be a palindrome by the code. Therefore, we received the message “STEPPETS is a palindrome”, as can be seen in the image below.

Palindrome in Python
Checking for a palindrome using a while loop.

Recursion

Another method for checking a palindrome in Python is by using recursion. This is where we check each element by breaking the sequence down into smaller problems. Recursion may seem similar to using a while loop, but there are some differences to note. While loops allow explicit control over the loop condition, but recursion implies implicit control. This is because the recursion continues until it matches the defined base case, but the loop variables are updated explicitly with a while loop. You can think of recursion as a function repeatedly calling itself until a base case is reached. To show this, we have the following code:

def is_palindrome(word):
    if len(word) <= 1:
        return True

    if word[0] == word[-1]:

        return is_palindrome(word[1:-1])
    else:
        return False


input_word = input("Enter a word or phrase: ")
if is_palindrome(input_word):
    print(f"{input_word} is a palindrome.")
else:
    print(f"{input_word} is not a palindrome.")

We still use the “is_palindrome” method here, but we define a base case, where the length of the sequence is equal to or less than 1. An if-else statement is used to compare the first and last characters. If they’re the same, they’re registered as palindromic, and the function is called recursively. If not, the false condition is returned and the recursion stops. We’ve used “RACECAR” as an example here, as you can see in the image, which is determined to be a palindrome. Recursion is useful because we don’t need to check the whole sequence if any 2 characters don’t match. Therefore, this can save a lot of time.

Palindrome in Python
We can use recursion to check for palindromes.

Built-in functions

There are two main built-in functions we can use to check a palindrome in Python – these are the reversed() function and the string slicing. These are described next.

Reversed() function

This function works in conjunction with a data list to reverse the sequence. These are then compared using the “==” operator. Let’s consider this code block:

def is_palindrome(word):
    word = word.replace(" ", "").lower()

    return list(word) == list(reversed(word))

input_word = input("Enter a word or phrase: ")
if is_palindrome(input_word):
    print(f"{input_word} is a palindrome.")

We define the palindrome method as before, then remove the spaces from the sequence to convert it to a list. Then, the “==” operator is used to compare the reversed list with the original list, and the result is printed. We used “56765” here, which is a palindrome.

Palindrome in Python
Using the Reversed() function to check for a palindrome.

String slicing

Another useful way to check a palindrome is by using the string slicing operator. Put simply, this is used to “slice” a string, or access defined substrings within a string. Generally, this is used by indicating the start and end of the string, as well as the step size (the magnitude of each increment). We can use a negative step size to iterate from the end of the sequence to the beginning, and, as such, check a palindrome. This is illustrated with the following code.

def is_palindrome(word):
    word = word.replace(" ", "").lower()

    return word == word[::-1]

input_word = input("Enter a word or phrase: ")
if is_palindrome(input_word):
    print(f"{input_word} is a palindrome.")
else:
    print(f"{input_word} is not a palindrome.")

We’ve defined the method and removed the spaces in the sequence as in the reversed() example. A negative step size is then used in the next line to create a reversed list. We then use the same “==” operator to compare this with the original sequence. By inputting “146432” as a test sequence, we’ve received the result that this isn’t a palindrome.

Palindrome in Python
Program to illustrate the use of string slicing operator to check for palindromes.

The Complexity of Palindrome Operations

The time complexity of the operations depends on the method used, as well as how they’re implemented. The complexity can be generally given as follows.

MethodTime ComplexityExplanation
While loopO(n)Proportional to string length, since at least half the characters must be compared
RecursionO(n) or O(1)If recursion stops early due to a false condition, then the complexity can approach constant-time
Reversed()O(n)The entire reverse string is compared, so complexity depends on the length
String slicingO(n)The string slice has the same characters as the original string

The space complexity of the operations can be described in the following table.

MethodSpace ComplexityExplanation
While loopO(1)No additional structures are needed as the comparison is iterative
RecursionO(1) or O(n)When recursion stops early, complexity approaches constant-time but generally is proportional to string length
Reversed()O(n)The reverse string must be stored
String slicingO(n)The string slice must be stored and is equivalent to the original string length

Palindrome in Python: Wrapping Up

Palindromes are not only interesting mathematical concepts but useful entities for solving programming problems and practicing your coding skills. A palindrome is defined as a sequence that reads the same backward as it does forwards. They can be checked for using built-in functions, such as string slicing or the reversed() function, but also by recursion or while loops. In essence, these methods either compare characters one by one or reverse a sequence and compare with the original to determine palindromic behavior.

Frequently Asked Questions

What is a palindrome?

A palindrome is a sequence of characters that reads the same backwards as it does forwards.

How are palindromes checked in Python?

We can check palindromes in Python by using built-in functions like string slicing and reversed(), but also recursively or using while loops.

What characters can a palindrome be?

Any characters can be palindromic, from numbers, to letters, to symbols or special characters.

 

 

What are the applications of palindromes?

Palindromes are used in checking text, data encryption, validating data and competitive programming.

How is palindrome checking optimized?

Recursion can be stopped early if a false condition is reached, which can help avoid unnecessary comparisons. You can also use memoization, where specific results of operations are stored in the cache. This avoids having to perform an operation with an identical output more than once.

What is the time complexity of palindrome checking?

This depends on the method and implementation, but generally equates to O(n). This can be O(1) for recursion, however, if the recursion is terminated early.

What is the space complexity of palindrome checking?

Generally, the space complexity is O(1) for while loops, and O(n) for all other methods. In the recursion best case, however, where it’s terminated early, the space complexity can approach O(1).

To top