Python – Test if list is Palindrome


When it is required to test if a list is a palindrome, a method is defined that reverses the string and checks if it is equal to the original string. Based on the result, relevant message is displayed on the console. A list comprehension and the ‘join’ method are used.

Example

Below is a demonstration of the same

def check_palindrome_list(my_str):
   if my_str == my_str[::-1]:
      print("The list is a palindrome")
   else:
      print("The list isn't a palindrome")

my_list = [77, 1, 56, 65, 1, 77]

print("The list is :")
print(my_list)

my_list = ' '.join([str(elem) for elem in my_list])
check_palindrome_list(my_list)

Output

The list is :
[77, 1, 56, 65, 1, 77]
The list is a palindrome

Explanation

  • A method named ‘check_palindrome_list’ is defined that takes a string as a parameter.

  • The string is reversed and it is compared to the original string.

  • Based on the result, relevant message is displayed on the console.

  • Outside the method, a list is defined and is displayed on the console.

  • It is iterated over and the ‘join’ method is used to join the elements and converted to a string.

  • The method is called by passing the required parameter.

  • The output is displayed on the console.

Updated on: 20-Sep-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements