Write a Python function to find the longest palindrome in a list of integers.
Posted by JackBrn
Last Updated: August 14, 2024
Finding the Longest Palindrome in a List of Integers
Palindromes are sequences that read the same forwards and backwards. This property can be applied to integers as well. In the context of a list of integers, we can create a Python function that identifies the longest palindromic number within that list. Below is a Python function that accomplishes this task:
def is_palindrome(number):
    """Check if a number is a palindrome."""
    str_num = str(number)
    return str_num == str_num[::-1]

def longest_palindrome(nums):
    """Find the longest palindrome in a list of integers."""
    longest = None
    max_length = 0
    
    for num in nums:
        if is_palindrome(num):
            num_length = len(str(num))
            if num_length > max_length:
                max_length = num_length
                longest = num

    return longest

# Example usage
if name == "main":
    numbers = [123, 121, 131, 4444, 56765, 78]
    result = longest_palindrome(numbers)
    print("The longest palindrome is:", result)
Explanation
1. Helper Function - is_palindrome: - This function takes an integer as input, converts it to a string, and checks if it reads the same forwards and backwards by comparing the string to its reverse (str_num[::-1]). 2. Main Function - longest_palindrome: - The function initializes two variables: longest to keep track of the longest palindrome found and max_length to store its length. - It iterates through each number in the provided list. If a number is confirmed to be a palindrome through the helper function, its length is compared to the current max_length. - If a longer palindrome is found, it updates max_length and sets longest to the current number. 3. Example Usage: - To showcase the function, a list of integers is defined and passed to the longest_palindrome function. The longest palindromic number is printed as output.
Conclusion
This function effectively identifies the longest palindromic integer in a list, providing a straightforward implementation that can be easily modified for additional features or performance enhancements. Each part of the code is structured to ensure clarity and easy understanding of the palindrome-checking process.