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