Newbi Q: Recursively reverse lists but NOT strings?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Oct 15 08:36:06 EDT 2007


On Mon, 15 Oct 2007 13:13:48 +0200, paul wrote:

> Dmitri O.Kondratiev schrieb:
>> Gary, thanks for lots of info!
>> Python strings are not lists! I got it now. That's a pity, I need two
>> different functions: one to reverse a list and one to reverse a string:
> Not necessarily, you can handle both cases in one function:
> 
> def reverse(xs):
>    if xs in [[], '']:
>      return xs
>    return (reverse (xs[1:])) + [xs[0], [xs[0]]][isinstance(list, xs)]
> 
> but this is evil(tm) and violates Rule #1, #2 of "import this" and
> several others.


I'm not sure if you consider the Zen of Python to be numbered from 1 or 
0, so here are the first three:


Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.

I'm not sure why you say that function violates two of those three. Well, 
okay, it's a bit ugly.

I would say it violates this rule:

There should be one-- and preferably only one --obvious way to do it.

Have I missed something? Nobody seems to have pointed out the existence 
of reversed(), which works on both lists and strings.


>>> ''.join(reversed("abc"))
'cba'
>>> list(reversed(range(3)))
[2, 1, 0]

It doesn't take much to make a more user-friendly version:


def myreversed(sequence):
    if isinstance(sequence, basestring):
        return type(sequence)().join(reversed(sequence))
    else:
        return type(sequence)(reversed(sequence))

(in fact, that's so simple I wonder why the built-in reversed() doesn't 
do that).


-- 
Steven



More information about the Python-list mailing list