Create an account

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Palindromes One-Liner

Python Palindromes One-Liner

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

This one-liner introduces another basic computer science term: palindromes. Similar to anagrams, palindromes are a popular coding 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.“ [source]

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).

Problem Formulation

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)?

  • Whitespace matters, i.e., 'ann a' is not considered a palindrome, but 'anna' is.
  • Capitalization matters, i.e., 'Anna' is not considered a palindrome, but 'anna' is.

Python Palindrome Checker in One Line

## One-Line Palindrome Checker
is_palindrome = lambda phrase: phrase == phrase[::-1]

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

If you don’t like one-liners and lambda functions, you can also define an explicit function:

def is_palindrome(phrase): return phrase == phrase[::-1]

Let’s check how this works next.

How the Python Palindrome Checker 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 whether the sequence of characters remains unchanged when reversed. To reverse the string, we use slicing.

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

Python Palindrome Checker Ignoring Whitespace and Capitalization

To check whether two strings are palindromes when ignoring capitalization and arbitrary whitespaces, first bring the string into a canonical form using ''.join(phrase.split()) and string.lower() to convert it to a lowercase string without whitespaces.

Then use the same expression string == string[::-1] to compare the string with its reverse representation using slicing with negative step size.

Here’s the code example:

def is_palindrome(phrase): # remove all whitespaces and lowercase string cleaned = ''.join(phrase.split()).lower() return cleaned == cleaned[::-1] print(is_palindrome("Anna"))
# True print(is_palindrome("An\n\n n \n\ta"))
# True

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

Forum Jump:

Users browsing this thread:
1 Guest(s)


Active Threads
Steam - Team Fortress 2 Update Released
Last Post: GilbertBib
Today 08:34 AM
» Replies: 1
» Views: 128
[Tut] Pandas cut() – A Simple Guide with...
Last Post: xSicKxBot
Yesterday 10:59 PM
» Replies: 0
» Views: 29
(Indie Deal) Grab Die Young for FREE & c...
Last Post: xSicKxBot
Yesterday 10:59 PM
» Replies: 0
» Views: 4
Blender 3 Released
Last Post: xSicKxBot
Yesterday 10:59 PM
» Replies: 0
» Views: 4
AppleInsider - Apple execs explain the d...
Last Post: xSicKxBot
Yesterday 10:58 PM
» Replies: 0
» Views: 3
Microsoft - ID@Xbox Winter Game Fest Dem...
Last Post: xSicKxBot
Yesterday 10:58 PM
» Replies: 0
» Views: 4
News - Talking Point: What Can This $120...
Last Post: xSicKxBot
Yesterday 10:58 PM
» Replies: 0
» Views: 5
Xbox Wire - Get Ready for the Alien Inva...
Last Post: xSicKxBot
Yesterday 10:58 PM
» Replies: 0
» Views: 5
News - Tsareena brings grass-fuelled glo...
Last Post: xSicKxBot
Yesterday 10:58 PM
» Replies: 0
» Views: 4
[Tut] User Registration in PHP with Logi...
Last Post: GilbertBib
Yesterday 01:45 PM
» Replies: 1
» Views: 53


Get the Deal of the Week at

Discord Server © 2012-2021