A curious bit of code...

Chris Angelico rosuav at gmail.com
Thu Feb 13 17:13:28 EST 2014


On Fri, Feb 14, 2014 at 8:33 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> Oh, it's not that bad!  All you have to do is handle the edge case of an
> empty string:
>
> s[::len(s)-1 if s else True]
>
> *ducks and runs*

And the edge case of the one-character string. Also, it's been noted
that calling the built-in function len() is slow, so I propose
changing that.

s[::(sys.getsizeof("\N{MATHEMATICAL BOLD CAPITAL
L}"+s)-sys.getsizeof("\N{MATHEMATICAL BOLD CAPITAL E}\N{MATHEMATICAL
BOLD CAPITAL N}") or 4)//4]

Note the elegance of using the word LEN across two string literals
(because string literals are fast) as a means of clearly describing
what we are doing - an optimization of the built-in len() function.

ChrisA



More information about the Python-list mailing list