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

56 Views Asked by At

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:

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']

1

There are 1 best solutions below

0
Barmar On BEST ANSWER

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)]