Check Palindromes in One Line Python. No For Loop. No Recursion.

"bob" == "bob"[::-1]

This one-liner introduces another basic computer science term: palindromes. Similarly to anagrams, palindromes are a popular interview question.

First things first: What is a palindrome?

“A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar or the number 10201.[1]

Here are a few fun examples:

  • “Mr Owl ate my metal worm”
  • “Was it a car or a cat I saw?”
  • “Go hang a salami, I’m a lasagna hog”
  • “Rats live on no evil star”
  • “Hannah”
  • “Anna”
  • “Bob”

Is there a short and concise one-liner solution in Python? (There is!)

But before you and I move on, I’m excited to present you my brand-new Python book Python One-Liners.

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

The Code

The problem is the following: given a sequence of characters (string) – is the reverse sequence of characters the same as the original sequence (that is – is the string a palindrome)?

## One-Liner
is_palindrome = lambda phrase: phrase == phrase[::-1]

## Result
print(is_palindrome("rats live on no evil star"))

Listing: One-liner solution to check whether a phrase is a palindrome.

What’s the output of these three function calls?

How It Works

The one-liner solution does not need any external library, it’s simple and straightforward. We define a lambda function that takes a single argument phrase – the string to be tested – and returns a Boolean value whether the sequence of characters remains unchanged when reversed. To reverse the string, we use slicing (see Chapter 3). Let’s quickly recap slicing:

Slicing is a Python-specific concept for carving out a range of values from sequence types such as lists or strings. Slicing is based on the concise notation [start:stop:step] to carve out a sequence starting in index “start” (inclusive) and ending in index “end” (exclusive). The third parameter “step” allows you to define the step size, i.e., how many characters from the original sequence your slice will skip before taking the next character (e.g. step=2 means that your slice will consist of only every other character). When using a negative step size, the string is traversed in reverse order.

Thus, the result of the one-liner code snippet is the following:

## Result
print(is_palindrome("anna")) # True
print(is_palindrome("kdljfasjf")) # False
print(is_palindrome("rats live on no evil star")) # True

Where to Go From Here

A thorough Python education is crucial for your success as a Python developer. For all coders with little time who love a daily coding challenge during their coffee break, I’ve written the book series “Coffee Break Python“. Check it out!

Need a break? Get Your Coffee Break Python!

2 thoughts on “Check Palindromes in One Line Python. No For Loop. No Recursion.”

    1. Yeah, you’re right. It’s just an approximate fun palindrome… 🙂
      Here’s how you could fix it:

      >>> s = “Mr Owl ate my metal worm”.lower().replace(” “,””)
      >>> print(s == s[::-1])

Leave a Comment

Your email address will not be published. Required fields are marked *