Open In App

Test if List is Palindrome – Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list we need to find that given list is a palindrome. For example a = [1, 2, 3, 2, 1] we need to check whether it is a palindrome or not so that the output should be ‘True’.

Using Slicing

We can check if a list is a palindrome by comparing it with its reverse using slicing ([::-1]). If the original list and its reversed version are equal list is a palindrome.

Python
a = [1, 2, 3, 2, 1]

# Check if the list is equal to its reversed version
is_pal = a == a[::-1]
print(is_pal)

Output
True

Explanation:

  • a[::-1] creates a reversed copy of the list, and a == a[::-1] checks if the original and reversed lists are identical.
  • If they are equal is_pal is True meaning the list is a palindrome otherwise it’s False.

Using reversed() and list()

We can check if a list is a palindrome by converting reversed iterator from reversed() into a list using list(). If original list matches this reversed list it is a palindrome.

Python
a = [1, 2, 3, 2, 1]

# Check if the list is equal to its reversed version using reversed() and list()
is_pal = a == list(reversed(a))
print(is_pal)

Output
True

Explanation:

  • reversed(a) returns an iterator that produces elements in reverse order which is then converted to a list using list(reversed(a)).
  • Original list is compared with its reversed version if they are equal is_pal is True indicating a palindrome.

Using a for loop

We can check if a list is a palindrome using a for loop by comparing elements from the start and end moving toward center. If all corresponding pairs match list is a palindrome otherwise it is not.

Python
a = [1, 2, 3, 2, 1]

# Compare elements from start and end moving towards the center
is_pal = all(a[i] == a[-(i+1)] for i in range(len(a) // 2))
print(is_pal)

Output
True

Explanation:

  • Generator expression iterates through the first half of the list comparing each element a[i] with its corresponding element from the end a[-(i+1)].
  • all() ensures that if all comparisons are True is_pal is True meaning list is a palindrome; otherwise it returns False


Next Article
Practice Tags :

Similar Reads