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
Python Program to Remove Palindromic Elements from a List
When it is required to remove palindromic elements from a list, list comprehension and the 'not' operator are used. A palindromic number reads the same forwards and backwards, like 121 or 9.
Example
Below is a demonstration of removing palindromic elements from a list ?
my_list = [56, 78, 12, 32, 4, 8, 9, 100, 11]
print("The list is:")
print(my_list)
my_result = [elem for elem in my_list if int(str(elem)[::-1]) not in my_list]
print("The result is:")
print(my_result)
Output
The list is: [56, 78, 12, 32, 4, 8, 9, 100, 11] The result is: [56, 78, 12, 32, 100]
How It Works
The algorithm works by checking if the reverse of each element exists in the original list. Here's the breakdown ?
str(elem)converts the number to a string[::-1]reverses the stringint(str(elem)[::-1])converts the reversed string back to an integernot in my_listchecks if the reversed number is NOT present in the original list
Alternative Method Using a Helper Function
For better readability, we can create a separate function to check if a number is palindromic ?
def is_palindrome(num):
return str(num) == str(num)[::-1]
my_list = [56, 78, 121, 32, 4, 8, 9, 100, 11]
print("The list is:")
print(my_list)
my_result = [elem for elem in my_list if not is_palindrome(elem)]
print("The result is:")
print(my_result)
The list is: [56, 78, 121, 32, 4, 8, 9, 100, 11] The result is: [56, 78, 32, 100]
Conclusion
Use list comprehension with string reversal to remove palindromic elements from a list. The helper function approach provides better code readability and reusability.
