Stepping backwards in for loop?
Andrew Dalke
dalke at acm.org
Sun Apr 15 12:07:09 EDT 2001
Steve Holden wrote:
>But there's no good reason why there shouldn't be a "reverse" function
which
>returns the reverse of any sequence, surely? The question then becomes
>whether a built-in function could improve on the efficiency of
>
>>>> def sreverse(s):
>... l = list(s)
>... l.reverse()
>... return "".join(l)
>...
>>>> sreverse("abcdefg")
>'gfedcba'
This doesn't work they way your English description says it should;
it doesn't work on "any sequence"
>>> sreverse([1, 2, 3])
Traceback (innermost last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 4, in sreverse
TypeError: first argument must be sequence of strings
>>>
because while a string *acts* like a list or tuple of characters,
it really isn't.
Andrew
dalke at acm.org
More information about the Python-list
mailing list