Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Test if list is Palindrome
A palindrome is a sequence that reads the same forwards and backwards. To test if a Python list is a palindrome, we can compare it with its reversed version using slice notation [::-1].
Method 1: Direct List Comparison
The simplest approach is to compare the original list with its reverse ?
def is_palindrome_list(data):
return data == data[::-1]
# Test with palindrome list
numbers = [1, 2, 3, 2, 1]
print("List:", numbers)
print("Is palindrome:", is_palindrome_list(numbers))
# Test with non-palindrome list
numbers2 = [1, 2, 3, 4, 5]
print("List:", numbers2)
print("Is palindrome:", is_palindrome_list(numbers2))
List: [1, 2, 3, 2, 1] Is palindrome: True List: [1, 2, 3, 4, 5] Is palindrome: False
Method 2: Using String Conversion
Convert the list to a string and check for palindrome using string reversal ?
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)
# Convert list to string for comparison
my_str = ' '.join([str(elem) for elem in my_list])
check_palindrome_list(my_str)
The list is: [77, 1, 56, 65, 1, 77] The list is a palindrome
Method 3: Two-Pointer Approach
Use two pointers from start and end, moving towards center ?
def is_palindrome_two_pointer(data):
left = 0
right = len(data) - 1
while left < right:
if data[left] != data[right]:
return False
left += 1
right -= 1
return True
# Test the function
test_lists = [
[1, 2, 1],
['a', 'b', 'a'],
[1, 2, 3, 4],
[]
]
for lst in test_lists:
result = is_palindrome_two_pointer(lst)
print(f"{lst} is palindrome: {result}")
[1, 2, 1] is palindrome: True ['a', 'b', 'a'] is palindrome: True [1, 2, 3, 4] is palindrome: False [] is palindrome: True
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Direct Comparison | O(n) | O(n) | Simple, readable code |
| String Conversion | O(n) | O(n) | Mixed data types |
| Two-Pointer | O(n) | O(1) | Memory efficiency |
Conclusion
Use direct list comparison data == data[::-1] for simplicity. The two-pointer approach is most memory-efficient, while string conversion works well for mixed data types.
Advertisements
