Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"".join(reversed(val)) vs val[::-1]...which is pythonic?

Tags:

python

So according to the Zen of Python ... Explicit is better than implicit...Sparse is better than dense...Readability counts...but then again Flat is better than nested...so then which is pythonic?

val = "which is pythonic?"
print("".join(reversed(val)))

or

print(val[::-1])

I'm just a Java programmer learning Python so I find this pythonic stuff interesting since there is no analog in the Java world AFAIK.

like image 706
non sequitor Avatar asked Nov 08 '09 04:11

non sequitor


1 Answers

My wife Anna has nicknamed x[::-1] "the Martian Smiley" -- I mostly bow to her (and her long experience in training &c, and studies in human psychology &c), when it comes to judging what's easy and natural for most people, and she absolutely loves the martial smiley. "Just walk it backwards" -- how much more direct, and high-abstraction, than the detailed specification of "reverse it and then join it back"!

Also, python -mtimeit is often a good judge of what's Pythonic: top Pythonistas, over the years, have of course tended to optimize what they most often needed and used, so a very substantial performance difference tells you what "goes with the grain" of the language and its top practitioners. And by that score, the martian smiley beats the detailed spec hands-down...:

$ python -mtimeit '"".join(reversed("hello there!"))'
100000 loops, best of 3: 4.06 usec per loop
$ python -mtimeit '"hello there!"[::-1]'
1000000 loops, best of 3: 0.392 usec per loop

order-of-magnitude performance differences just don't leave that much room for doubt!-)

like image 200
Alex Martelli Avatar answered Sep 18 '22 18:09

Alex Martelli