Search code examples
pythonlist-comprehensionpalindrome

Why the list generated by a list comprehension is empty


First, sorry for my poor English and layout. I'm a Python beginner in China and this is the first question I've asked using English.

Here's the question:

I'm trying to generate palindrome number like 121 using filter(is_palindrome, range(1, 1000)). The code closely related to this question is l = [int(i) for i in str(n)] in the is_palindrome(n) function. The debugger showed that when n = 11, l = [] instead of [1, 1], and then IndexError: list index out of range happened at if l[0] != l[-1].

I want to know why and how to let it be [1, 1].

Source Code:

def is_palindrome(n):
    p = True
    l = [int(i) for i in str(n)]
    while len(l) != 1:
        if l[0] != l[-1]:
            p = False
            break
        l.pop(0)
        l.pop(-1)
    return p
print(list(filter(is_palindrome, range(1, 1000))))

p.s. I know there is an easier way like return str(n) == str(n)[::1] but I just want to try another one :)


Solution

  • So How do you track your error , Try this :

    Just put a print and see where function is failing at Index Error :

    def is_palindrome(n):
        p = True
        l = [int(i) for i in str(n)]
        while len(l) != 1:
            print("l",l)
            if l[0] != l[-1]:
                p = False
                break
            l.pop(0)
            l.pop(-1)
        return p
    print(list(filter(is_palindrome, range(1, 1000))))
    

    output:

    l [1, 0]
        if l[0] != l[-1]:
    l [1, 1]
    IndexError: list index out of range
    l []
    

    As you can see clearly that when l is [] (empty) then it's giving error ,Now let's fix it and run the code

    Here is your function after some modification:

    def is_palindrome(n):
        p = True
        l = [int(i) for i in str(n)]
    
        while len(l) != 1 and l!=[]:
            if l[0] != l[-1]:
                p = False
                break
            l.pop(0)
            l.pop(-1)
        return p
    print(list(filter(is_palindrome, range(1, 1000))))
    

    output:

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]