Skip to content
Related Articles

Related Articles

Python Program to Remove Palindromic Elements from a List

View Discussion
Improve Article
Save Article
  • Last Updated : 23 Aug, 2021
View Discussion
Improve Article
Save Article

Given a list, the task here is to write Python programs that can remove all the elements which have palindromic equivalent element present in the list.

Examples:

Input : test_list = [54, 67, 12, 45, 98, 76, 9]

Output : [12, 98]

Explanation : 67 has 76 as palindromic element, both are omitted.

Input : test_list = [54, 67, 12, 45, 98, 76, 9, 89]

Output : [12]

Explanation : 98 has 89 as palindromic element, both are omitted.

Method 1 : Using str(), list comprehension and int()

In this, elements are first converted to string using str(), reversed and reconverted to integer using int() and occurrence of palindromes is checked, if present, both the element and its palindrome are omitted from result.

Example:

Python3




# initializing list
test_list = [54, 67, 12, 45, 98, 76, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# reversing and comparing for presence using in operator
res = [ele for ele in test_list if int(str(ele)[::-1]) not in test_list]
 
# printing result
print("List after palindromic removals ? : " + str(res))

Output:

The original list is : [54, 67, 12, 45, 98, 76, 9]

List after palindromic removals ? : [12, 98]

Method 2 : Using filter(), str() and int()

In this, we perform the task of filtering each element using filter(). str() and int() is used for the same function as in the above method.

Example:

Python3




# initializing list
test_list = [54, 67, 12, 45, 98, 76, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# reversing and comparing for presence using in operator
res = list(filter(lambda ele: int(str(ele)[::-1]) not in test_list, test_list))
 
# printing result
print("List after palindromic removals ? : " + str(res))

Output:

The original list is : [54, 67, 12, 45, 98, 76, 9]

List after palindromic removals ? : [12, 98]


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!