Newbi Q: Recursively reverse lists but NOT strings?

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Oct 15 02:30:02 EDT 2007


On Mon, 15 Oct 2007 02:11:27 -0400, Victor B. Gonzalez wrote:

> On Sunday 14 October 2007 5:06:19 pm Dmitri O.Kondratiev wrote:
>> The function I wrote (below) reverses lists all right:
>>
>> def reverse(xs):
>>     if xs == []:
>>         return []
>>     else:
>>         return (reverse (xs[1:])) + [xs[0]]
>>
>> >>> reverse ([1,2,3])
>>
>> [3, 2, 1]
>>
>> Yet when I try to reverse a string I  get:
>> >>> reverse ("abc")
>>
>> ...
>> ...
>> ...
>>
>>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>>
>>     return (reverse (xs[1:])) + [xs[0]]
>>
>>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>>
>>     return (reverse (xs[1:])) + [xs[0]]
>>
>>   File "C:\wks\python-wks\reverse.py", line 2, in reverse
>>
>>     if xs == []:
>>
>> RuntimeError: maximum recursion depth exceeded in cmp
>>
>>
>>
>> What's wrong? Why recursion never stops?

Becauese you test if `xs` is an empty list which is never true when you
call the function with a string.  So it never ends.  '' != []

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list