Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python function to return a new list containing the strings that are palindromes and have an even length

Practice Question:

Given a list of strings, write a Python function to return a new list containing the strings that are palindromes and have an even length.

For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Input: ["radar", "level", "python", "noon", "racecar"]
Output: ["noon", "racecar"]

Write a function called even_length_palindromes that takes a list of strings as input and returns a new list containing only the palindromic strings with an even length.

def is_palindrome(string):
    if(string==string[::-1]):
        return(string)
    return()    
def even_length_palindromes(string):
    return(sample for sample in string if len(is_palindrome(sample))%2==0) 

print(list(even_length_palindromes(["radar", "level", "python", "noon", "racecar"])))

the qutput generated was ['python', 'noon'] insted of ['noon']

>Solution :

Return a boolean from is_palindrome(), as its name suggests. Then test for even length separately.

You also need to use a list comprehension in even_length_palindromes(), since the description says it should return a list, not a generator.

def is_palindrome(string):
    return string == string[::-1]

def even_length_palindromes(string_list):
    return [sample for sample in string_list if len(sample) % 2 == 0 and is_palindrome(sample)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading