Newbi Q: Recursively reverse lists but NOT strings?

paul paul at
Mon Oct 15 13:13:48 CEST 2007

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.

> Ok. Now regarding in-place reversal of a list:
  why this ? :
>>>> ls = [1,2,3].reverse()
>>>> ls
>>>> print [1,2,3].reverse()
> None
> I mean, why ls is empty after assignment?
That's what "in-place" means, [].reverse() changes the list in-place and 
does not return the list to the caller.


More information about the Python-list mailing list