[Tutor] Problem with if statements and else statements

Peter Otten __peter__ at web.de
Mon May 29 01:36:11 EDT 2017


Alex Kleider wrote:

> On 2017-05-28 13:13, Mats Wichmann wrote:
> 
>> FWIW, if checking for multiples, you could also write:
>> 
>> if Month in ['January', '1']:
> 
> Would
> 
>>>> if Month in {'January', '1'}:
> 
> be even better?  (regarding efficiency perhaps? Trivial point, I know,
> but just wondering.)

Yes, according to timeit there is already a significant difference:

$ python3 -m timeit -s 'month = "September"' 'month == "January" or month == 
"1"'
10000000 loops, best of 3: 0.126 usec per loop
$ python3 -m timeit -s 'month = "September"' 'month in ["January", "1"]'
10000000 loops, best of 3: 0.108 usec per loop
$ python3 -m timeit -s 'month = "September"' 'month in {"January", "1"}'
10000000 loops, best of 3: 0.0684 usec per loop

As the size of the list/set grows you'll see the effects of O(N) versus 
O(1):

$ python3 -m timeit -s 'N = 10**6; numbers = list(range(N))' 'N in numbers'
10 loops, best of 3: 32.5 msec per loop
$ python3 -m timeit -s 'N = 10**6; numbers = set(range(N))' 'N in numbers'
10000000 loops, best of 3: 0.0921 usec per loop




More information about the Tutor mailing list