Reversing a string

Evan Klitzke evan at yelp.com
Sun Jul 1 12:51:20 EDT 2007


On 1 Jul 2007 11:09:40 GMT, Martin Durkin <nospam at williamsdurkin.co.uk> wrote:
> Duncan Booth <duncan.booth at invalid.invalid> wrote in
> news:Xns996067AFF71DDduncanbooth at 127.0.0.1:
>
> > Martin Durkin <nospam at williamsdurkin.co.uk> wrote:
> >
> >>>>>> def rev(x):
> >>>             mylist = []
> >>>             for char in x:
> >>>                  mylist.append(char)
> >>>             mylist.reverse()
> >>>             for letter in mylist:
> >>>                  print letter
> >>>
> >>> However, compare the incredible difference in clarity and elegance
> >>> between that and:
> >>>
> >>>> >>> print "\n".join("spam"[::-1])
> >>>
> >>
> >> OK, maybe I'm missing the point here as I'm new to Python. The first
> >> one seems clearer to me. What am I missing?
> >>
> > I think all you are missing is familarity with Python, but I too don't
> > like one-liners simply for their own sake.
> >
>
> 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

-- 
Evan Klitzke <evan at yelp.com>



More information about the Python-list mailing list