palindrome iteration

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Aug 28 06:51:16 EDT 2010


On Sat, 28 Aug 2010 09:48:47 +0100, Ian wrote:

> On 27/08/2010 21:51, Jussi Piitulainen wrote:
>> Meanwhile, I have decided to prefer this:
>>
>> def palindromep(s):
>>      def reversed(s):
>>          return s[::-1]
>>      return s == reversed(s)
> I like this.

It's silly, needlessly complicated, and inefficient. Why create a *one 
line* nested function that only gets called once? Every single time you 
call the function, it has to create the inner function again, then call 
it once, then throw it away. Admittedly Python does recreate the inner 
function from pre-compiled parts, which is quick, but still, it doesn't 
gain you anything that a simple comment wouldn't give:

def palindromep(s):
    return s == s[::-1]  # Compare s to its reverse.


> s[::-1] is obscure and non-obvious, especially to Python noobs.

*Only* to Python noobs. Slicing is fundamental to Python, and using a 
slice of [::-1] to reverse something is a basic Python idiom.


> This makes it clear what is going on and why at a cost of very little
> code.
> 
> Very helpful to the maintenance programming in 18 months time!

Only if writing three lines when one would do is your definition of 
"helpful".




-- 
Steven



More information about the Python-list mailing list