w3resource

Python: Find palindromes in a given list of strings using Lambda


Write a Python program to find palindromes in a given list of strings using Lambda.

According Wikipedia - A palindromic number or numeral palindrome is a number that remains the same when its digits are reversed. Like 16461, for example, it is "symmetrical". The term palindromic is derived from palindrome, which refers to a word (such as rotor or racecar) whose spelling is unchanged when its letters are reversed. The first 30 palindromic numbers (in decimal) are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202,...

Sample Solution:

Python Code :

# Create a list 'texts' containing strings
texts = ["php", "w3r", "Python", "abcd", "Java", "aaa"]

# Display a message indicating that the following output will show the original list of strings
print("Orginal list of strings:")
print(texts)  # Print the contents of the 'texts' list

# Use the 'filter()' function with a lambda function to filter palindromes from the list
# Filter elements from 'texts' using the lambda function to keep strings that are palindromes
# The lambda function checks if a string is equal to its reverse by joining its characters in reverse order
result = list(filter(lambda x: (x == "".join(reversed(x))), texts))

# Display the list of palindromes obtained from the original list of strings
print("\nList of palindromes:")
print(result)  # Print the filtered 'result' list 

Sample Output:

Orginal list of strings:
['php', 'w3r', 'Python', 'abcd', 'Java', 'aaa']

List of palindromes:
['php', 'aaa']

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the second lowest grade of any student(s) from the given names and grades of each student using lists and lambda.
Next: Write a Python program to find all anagrams of a string in a given list of strings using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.