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.
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!-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With