Write a Python function to find the longest palindrome in a list of strings.
Posted by SamPetr
Last Updated: August 16, 2024
## Finding the Longest Palindrome in a List of Strings A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). To create a function that finds the longest palindrome in a list of strings, consider the following implementation in Python.
Implementation
The function longest_palindrome below iterates through each string in the provided list, checks if it is a palindrome, and keeps track of the longest one found.
def is_palindrome(s):
    """Check if a given string is a palindrome."""
    return s == s[::-1]

def longest_palindrome(strings):
    """Find the longest palindrome in a list of strings."""
    longest = ""
    
    for s in strings:
        # Check if the current string is a palindrome
        if is_palindrome(s):
            # Update longest if the current palindrome is longer
            if len(s) > len(longest):
                longest = s
                
    return longest

# Example usage
strings_list = ["racecar", "hello", "level", "world", "deified", "notapalindrome"]
result = longest_palindrome(strings_list)
print(f"The longest palindrome is: '{result}'")
Explanation
1. Palindrome Check: The is_palindrome function takes a string and checks if it reads the same backward using slicing (s[::-1]). 2. Finding the Longest Palindrome: The longest_palindrome function initializes an empty string longest. It then iterates through each string in the input list strings. If a string is identified as a palindrome and its length exceeds the current longest palindrome, it updates longest. 3. Returning the Result: After iterating through the list, the function returns the longest palindrome found.
Example Usage
In the provided example, the list contains several strings, and the function will identify "racecar", "level", and "deified" as palindromes, with "deified" being the longest. This approach effectively finds the longest palindrome with a time complexity of O(n * m), where n is the number of strings in the list and m is the average length of the strings due to the palindrome check.