Search code examples
pythonpalindrome

I need help on my palindrome programm in python


This is my code currently:

  def main():
        list1 = [(x) for x in input()]
        if (list1 == list1.reverse()):
            print("The sentence is a palindrome.")
        else:
            print("The sentence is not a palindrome.")

    main()

And it doesn't work. I've made the following adjustments when I found them on the forums and it worked:

def main():
    list1 = [(x) for x in input()]
    if (list1 == list1[::-1]):
        print("The sentence is a palindrome.")
    else:
        print("The sentence is not a palindrome.")

main()

My question is, why doesn't the first version work? It always prints: The sentence is not a palindrome.


Solution

  • list1.reverse() works in-place. It reverses list1 and returns None, so you're comparing a list to None and it's always False...

    The second code returns a reversed copy of list1 as a list so both lists are compared and it works.

    Note: another trap would be to compare with list1 == reversed(list1). That would work in python 2, but not in python 3 since reversed has been turned into an iterable.

    Aside: don't do list1 = [(x) for x in input()] but just list1 = list(input())

    (or as some nice commenter suggested, work directly with str type, no need to convert to strings at all, [::-1] operation also applies on strings, so just change to list1 = input() in your second code snippet)