Open In App

Python Program to Remove Palindromic Elements from a List

Last Updated : 08 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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]

Time Complexity: O(n)
Auxiliary Space: O(n)

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]

Time Complexity: O(n) where n is the number of elements in the list “test_list”. The filter(), str() and int() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads