Newbi Q: Recursively reverse lists but NOT strings?

Chris Mellon arkanes at gmail.com
Mon Oct 15 13:27:54 EDT 2007


On 10/15/07, Steven D'Aprano <steve at remove-this-cybersource.com.au> wrote:
> 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).
>
>

Probably because reversed()'s primary use case is iteration, and it
doesn't make sense to do the magic to return full objects there.

The use case where you need to reverse a string or a list, with no
context about what it will be, and where you're not iterating over the
result (so a simple reversed() isn't practical) seems to be pretty
obscure to me, so that there's not an obvious answer isn't surprising.
There is the slightly non-obvious answer of sequence[::-1], though,
which I think is perfectly satisfactory.



More information about the Python-list mailing list