Python Program to Remove Palindromic Elements from a List

PythonServer Side ProgrammingProgramming

When it is required to remove palindromic elements from a list, list comprehension and the ‘not’ operator are used.

Example

Below is a demonstration of the same

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]

Explanation

  • A list is defined and displayed on the console.

  • A list comprehension is used to iterate over the list, and convert the element to string first and then to an integer and reverse it.

  • It is checked to see that the element is not in the list.

  • This is assigned to a variable.

  • This is displayed as output on the console.

raja
Published on 20-Sep-2021 08:12:02
Advertisements