palindrome function

Mensanator mensanator at aol.com
Fri Jul 11 19:20:47 EDT 2008


On Jul 11, 5:34 pm, Denis Kasak <denis.kasak2718281... at gmail.com>
wrote:
> On Sat, Jul 12, 2008 at 12:22 AM, kdt <dorjeta... at googlemail.com> wrote:
>
>  > Hi all,
>  >
>  > Can someone please explain to me why the following evaluates as false?
>  >
>  >>>>list=['a','n','n','a']
>  >>>>list==list.reverse()
>  >>>>False
>  >
>  > I'm stumped :s
>
> Read the documentation on list.reverse().
>
> Basically, it reverses the list in place, so it modifies the list which
> called it. It does not return a /new/ list which is a reversed version
> of the original, as you expected it to. Since it doesn't return anything
> explicitly, Python makes it return None. Hence, the comparison you are
> doing is between the original list and a None, which is False, naturally.
> Try this:
>
> spam = ['a', 'n', 'n', 'a']
> eggs = spam[:]
> if spam.reverse() == eggs:
>     print "Palindrome"

You could also do

>>> spam = ['a','n','n','a']
>>> if spam == [i for i in reversed(spam)]:
	print "Palindrome"


>
> Also, 'list' is a really bad name for a list, since this is the name of
> the builtin type object for the list type.
>
> --
> Denis Kasak




More information about the Python-list mailing list