-1

The user enters a word. The program must compare the words and inform you whether or not it is a palindrome. Here is what I have so far:

string = list((input("Enter a word: ")))
print (string)
x = string.reverse()
print(x)
if x == string:
    print "Your word is a palindrome"
else:
    print "Your word is not a palindrome"

From what I have read on stackoverflow, the List.reverse() only reverses the sequence in place and does not return it. Why can I not assign the reversed list to a variable and then print?

This is what it returns when I enter a palindrome:

Enter a word: 'ror'
['r', 'o', 'r']
None
Your word is not a palindrome
Psidom
  • 209,562
  • 33
  • 339
  • 356
K.Doe
  • 39
  • 1
  • 9
  • `reverse` reverses in place... – Andrew Li Sep 13 '16 at 23:46
  • The reason your test always hits the else branch is that you are misusing the `list.reverse()` method. This method doesn't return a reversed list, it reverses the list in place and returns nothing. When you run `x = string.reverse()`, the list `string` has its order reversed, and `x` is set to `None`. But as Moinuddin Quadri points out, there are better ways to reverse a string than converting it to a list. – David Scarlett Sep 13 '16 at 23:51
  • @Prune - that's not a duplicate. It's a recursive function with the error being that the recursive call isn't returned, while this question is a reassignment of an in-place operation becoming `None`. – TigerhawkT3 Sep 13 '16 at 23:51
  • reverse will reverse the calling list, but doesn't return anything which is why X is getting set to None. – Tony Sep 13 '16 at 23:52
  • @TigerhawkT3: OOPS. Wrong link. I'll have to withdraw the closure vote. – Prune Sep 13 '16 at 23:53

1 Answers1

0

You do not need to convert string to list and then reverse it.

You can simply reverse a string by doing your_string[::-1]. For example:

>>> x = 'abcdef'
>>> x[::-1]
'fedcba'

Save the reversed value with a variable and use that variable within your code.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126