Python program to check if number is palindrome (one-liner)


Generally, palindrome is a word, phrase, number, or other sequence of characters that reads the same forwards and backwards. In the context of a Python program, a palindrome usually refers to a string or number that remains the same when its characters or digits are reversed.

For example, let’s consider the word Madam, when we read this word from left to right and right to left the word will be the same. So this is a palindrome.

There are different approaches to find if the given number is palindrome in python. First let’s see the basic approach without using the one-liner code.

Basic approach

In this example we are creating the basic approach of checking if the given number is palindrome by using the string slicing.

Here we are converting the given input number into string and then applying the string slicing to reverse the number. Then compare the reversed number and the original number using the equal to operator.

def is_palindrome(number):
   return str(number) == str(number)[::-1]
num = 10001
if is_palindrome(num):
   print(num,"is a palindrome.")
else:
   print(num,"is not a palindrome.")

Output

10001 is a palindrome.

One-liner approach using lambda

One-liner programs provide a concise way to check or perform the required operation on the given input data. We can modify the input values and use them to test other strings or numbers for operations properties.

Lambda functions are also known as anonymous functions, which are used to create small, one-line functions in Python without using the def keyword. They are defined using the lambda keyword, followed by a comma-separated list of parameters, a colon (:), and the expression or operation to be executed.

The following is the syntax for using lambda function

lambda parameters:expression

Example

In this example of one-liner program, a lambda function is defined with the name is_palindrome. This function takes a number num as input and compares it with its reversed number by applying the string slicing using the [::-1] slicing notation If the original number and its reverse number are equal, it means the number is a palindrome, and the lambda function returns True otherwise, it returns False.

is_palindrome = lambda num: str(num) == str(num)[::-1]
num = 12121
if is_palindrome(num):
   print(num,"is a palindrome.")
else:
   print(num,"is not a palindrome.")

Output

12121 is a palindrome.

Updated on: 19-Oct-2023

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements