Most efficient way to evaluate the contents of a variable.

B

bdude

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
 
S

Stargaming

bdude said:
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

Most maintenance-efficient, that is.
 
C

Carsten Haese

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[/QUOTE]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,214
Latest member
JFrancisDavis

Latest Threads

Top