Reversing a string

Jay Loden python at jayloden.com
Sun Jul 1 13:32:37 EDT 2007


Evan Klitzke wrote:
>
>> I guess that's it. The first one reads more like a textbook example which
>> is about where I am at. Is there any speed benefit from the one liner?
> 
> The one line is quite a bit faster:
> 
> evan at thinkpad ~ $ python -m timeit 's = "onomatopoeia"; s = s.join(s[::-1])'
> 100000 loops, best of 3: 6.24 usec per loop
> 
> evan at thinkpad ~ $ python -m timeit '
>> def rev(x):
>>     mylist = []
>>     for char in x:
>>         mylist.append(char)
>>     mylist.reverse()
>>     return "".join(mylist)
>>
>> s = "onomatopoeia"
>> s = rev(s)'
> 100000 loops, best of 3: 9.73 usec per loop


For what it's worth, with python 2.5 on my Macbook:

[jloden at macbook jloden]$ python -m timeit 's = "onomatopoeia"; s = s.join(s[::-1])'
100000 loops, best of 3: 5.2 usec per loop

[jloden at macbook jloden]$ python -m timeit ' 
> def rev(x):
>   mylist = list(x)
>   mylist.reverse()
>   return "".join(mylist)
> 
> s = "onomatopoeia"
> s = rev(s)'
100000 loops, best of 3: 3.94 usec per loop 

Note that in the second version, I changed the code a little bit so that it no longer iterates over every char in the string and instead just calls lis() to convert it to a list of chars in order to call list.reverse() on it. 

-Jay



More information about the Python-list mailing list