A curious bit of code...

Neil Cerutti neilc at norwich.edu
Thu Feb 13 16:01:10 EST 2014


On 2014-02-13, Zachary Ware <zachary.ware+pylist at gmail.com> wrote:
> In a fit of curiosity, I did some timings:
>
> 'and'ed indexing:
>
> C:\tmp>py -m timeit -s "key = '<test>'" "key[0] == '<' and key[-1] == '>'"
> 1000000 loops, best of 3: 0.35 usec per loop
>
> C:\tmp>py -m timeit -s "key = '<test'" "key[0] == '<' and key[-1] == '>'"
> 1000000 loops, best of 3: 0.398 usec per loop
>
> C:\tmp>py -m timeit -s "key = 'test>'" "key[0] == '<' and key[-1] == '>'"
> 1000000 loops, best of 3: 0.188 usec per loop
>
> C:\tmp>py -m timeit -s "key = 'test'" "key[0] == '<' and key[-1] == '>'"
> 10000000 loops, best of 3: 0.211 usec per loop
>
> C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'"
> Traceback (most recent call last):
>   File "P:\Python34\lib\timeit.py", line 292, in main
>     x = t.timeit(number)
>   File "P:\Python34\lib\timeit.py", line 178, in timeit
>     timing = self.inner(it, self.timer)
>   File "<timeit-src>", line 6, in inner
>     key[0] == '<' and key[-1] == '>'
> IndexError: string index out of range

The corrected version

key and key[0] == '<' and key[-1] == '>'

probably still wins the Pretty Unimportant Olympics.

-- 
Neil Cerutti




More information about the Python-list mailing list