0

I can't figure out why my if-else statement doesn't run as expected. I've tried to create code to test for a palindromic string. My print functions show me that the reverse method works, but when I get to the comparison stage I can't get it to return True.

Here is the code:

def is_palindrome(a):
    myList = []

    for i in a:
        myList.append(i)

    print myList
    new = myList.reverse()
    print myList
    print new

    if myList == new:
        return True
    else:
        return False


print is_palindrome("radar")

This returns False. I have also tried changing the if statement to if myList is new: but unfortunately it still returns False.

Any insight appreciated!

arumiat
  • 123
  • 2
  • 9

1 Answers1

5

list.reverse() is in-place, meaning it reverses the list it is called upon but doesn't return anything.

The line print new should print None, and therefore myList == new will be False.

Instead, use [::-1] which is not in-place and returns a new, reversed list, or use an easier way to detect a palindrome, for example:

def is_palindrome(iterable):
    return iterable == iterable[::-1]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Thanks. I understand the concept of in-place, but why doesn't it return/ save that list to the variable `new`? EDIT: Just saw your followup, thank you! – arumiat Jul 10 '16 at 11:07
  • @arumiat Because by definition, when a method is "in-place" it doesn't return anything. – DeepSpace Jul 10 '16 at 11:08
  • @arumiat Because the line `new = myList.reverse()` doesn't return anything, it just changed myList. I'm not sure you do understand the concept... – Tim Jul 10 '16 at 11:08
  • @DeepSpace okay, but `reversed` does not return a new list... so the comparison won't work... – Jon Clements Jul 10 '16 at 11:12
  • 1
    @DeepSpace nope - it never has in 2.x or 3.x... (sounds like you're confusing it with `map`/`zip` etc... differences between 2 and 3) – Jon Clements Jul 10 '16 at 11:14
  • And you could eliminate copy altogether: def is_palindrome(seq): return all(x == y for x, y in zip(iter(seq), reversed(seq))) – Adam Sosnowski Jul 10 '16 at 11:27
  • And you could eliminate duplicated comparisons: def is_palindrome(seq): return all(seq[i] == seq[-i-1] for i in range(len(seq) / 2)) – Adam Sosnowski Jul 10 '16 at 11:28