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.
list1.reverse()works in-place. It reverseslist1and returnsNone, so you're comparing a list toNoneand it's alwaysFalse...The second code returns a reversed copy of
list1as alistso 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 sincereversedhas been turned into an iterable.Aside: don't do
list1 = [(x) for x in input()]but justlist1 = list(input())(or as some nice commenter suggested, work directly with
strtype, no need to convert to strings at all,[::-1]operation also applies on strings, so just change tolist1 = input()in your second code snippet)