Search code examples
pythonalgorithmpython-2.7palindrome

Why can I not check for comparisons on strings without them being lists?


I was working on the popular palindrome question in python. I originally thought this code would be enough:

def is_palindrome(input_string):
    rev_str = reversed(input_string)

    if rev_str == input_string:
        return True
    else:
        return False

But only some of the examples ended up being correct. I checked the solution and I had to change the strings into lists for the code to work properly but I don't understand why.

def is_palindrome(input_string):
    rev_str = reversed(input_string)

    if list(rev_str) == list(input_string):
        return True
    else:
        return False

Any help on understanding why this is the case would be really helpful.


Solution

  • The problem is that reversed("hello") returns a reversed iterator object, not "olleh." This is to save memory, as it doesn't need to compute all the letters until you need them.

    >>> reversed("hello")
    <reversed object at 0x02A7B170>
    

    If this confuses you, look into what iterators are.

    If you want to reverse a string, you can just do

    s[::-1]
    

    Where s is your string.