Most efficient way to evaluate the contents of a variable.

Carsten Haese carsten at uniqsys.com
Fri Jul 13 01:26:46 EDT 2007


On Fri, 13 Jul 2007 06:37:19 +0200, Stargaming wrote
> bdude schrieb:
> > Hey, I'm new to python and am looking for the most efficient way to
> > see if the contents of a variable is equal to one of many options.
> > 
> > Cheers,
> > Bryce R
> >
> 
> if var in ('-h', '--hello', '-w', '--world'):
>      pass

Unless the list of choices is trivially small, a set performs membership tests
faster than a tuple:

$ python -m timeit -s "s=('eggs','spam','parrot')" "'eggs' in s"
10000000 loops, best of 3: 0.177 usec per loop

$ python -m timeit -s "s=('eggs','spam','parrot')" "'spam' in s"
1000000 loops, best of 3: 0.219 usec per loop

$ python -m timeit -s "s=('eggs','spam','parrot')" "'parrot' in s"
1000000 loops, best of 3: 0.262 usec per loop

$ python -m timeit -s "s=('eggs','spam','parrot')" "'python' in s"
1000000 loops, best of 3: 0.303 usec per loop

$ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'eggs' in s"
10000000 loops, best of 3: 0.192 usec per loop

$ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'spam' in s"
10000000 loops, best of 3: 0.192 usec per loop

$ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'parrot' in s"
10000000 loops, best of 3: 0.192 usec per loop

$ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'python' in s"
10000000 loops, best of 3: 0.189 usec per loop

--
Carsten Haese
http://informixdb.sourceforge.net



More information about the Python-list mailing list