Qwerty
Qwerty

Reputation: 41

How to Check if a String is a Palindrome

My codes are below. I am inexperienced coder, I think the problem is with the .join(reversed()) part. However, I can't figure out why. I need someone else to check this again, maybe I missed out something.

def is_palindrome(alist):
    truth = []
    for i in alist:
        i.lower()
        i.replace(" ","")
        x = "".join(reversed(i))
        if i == x:
            truth.append(True)
        else:
            truth.append(False)
    return truth
test_list = ['Stats', 'A nut for a jar of Tuna', 'I eat apples']
print(is_palindrome(test_list))
print(test_list)

The results given is:

[False, False, False]

It is supposed to be:

[True,True,False]

Anyone have any ideas where I went wrong?

Upvotes: 3

Views: 99

Answers (2)

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

Both .lower() and .replace(...) are not in place

def is_palindrome(alist):
    truth = []
    for i in alist:
        i=i.lower()
        i=i.replace(" ","")
        x = "".join(reversed(i))
        truth.append(i == x)
    return truth
test_list = ['Stats', 'A nut for a jar of Tuna', 'I eat apples']
print(is_palindrome(test_list))
print(test_list)

Upvotes: 6

Tanay Karve
Tanay Karve

Reputation: 2285

The lower() and replace() functions are not in-place.

You must assign their return value to i.

i=i.lower()
i=i.replace(" ","")

Output:

[True, True, False]                                
['Stats', 'A nut for a jar of Tuna', 'I eat apples']

Upvotes: 4

Related Questions