Ram gowtham
Ram gowtham

Reputation: 1

To check whether palindrome or not

On compilation of this code it shows None as Output

list = ["malayalam"]
reverse_list = list.reverse()
print(reverse_list)
while list == reverse_list:
    print('the answer is palindrome')

Upvotes: 0

Views: 174

Answers (4)

prime
prime

Reputation: 15594

Why it says None ?

Here's an example,

>>> mylist = [1, 2, 3, 4, 5]
>>> mylist
[1, 2, 3, 4, 5]

>>> mylist.reverse()
None

>>> mylist
[5, 4, 3, 2, 1]

As you can see, calling mylist.reverse() returned None, but modified the original list object. This implementation was chosen deliberately by the developers of the Python standard library:

The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence. Source

So in your case it should print None, and since list == reverse_list is evaluated to false nothing other than the previous will print. Why is explained earlier.

Hope you want to check a word is palindrome or not, if so you don't need a list for that. Below solution uses some inbuilt functions to achieve that.

word = "malayalam"
rev = ''.join(reversed(word))

if (word == rev):
    print('the answer is palindrome')
else:
    print('the answer is not a palindrome')

See this working example

Upvotes: 0

Bakhrom Rakhmonov
Bakhrom Rakhmonov

Reputation: 702

You're using wrong reverse function in python try this one

def is_palindrome1(st):
    ln = len(st)
    for i in range(ln//2):
        if st[i] != st[ln - 1 - i]:
            return False
    return True

def is_palindrome2(st):
    lst=list("malayalam")
    reversed_list=list(reversed(lst))
    return lst == reversed_list

def is_palindrome3(st):
    p1 = st[:len(st)//2]
    p2 = st[(len(st)+1)//2:]
    return p1 == p2

lst = "malayalam"

if is_palindrome1(lst):
    print('the answer is palindrome')
else:
    print('not palindrome')

Upvotes: 1

sam46
sam46

Reputation: 1271

reverse() mutates the original list and doesn't return a new one. so reverse_list=list.reverse() makes reverse_list None.

Here's an answer you might want to check out How to check for palindrome using Python logic

Upvotes: 1

bigbounty
bigbounty

Reputation: 17408

Instead reverse the string itself

Use the following

>>> a = "Malayalam"
>>> rev = a[::-1]
>>> if a == rev:
>>>   print("palindrome")
>>> else:
>>>   print("Not a palindrome")

Upvotes: 0

Related Questions