[Tutor] equality check difference

Albert-Jan Roskam fomcl at yahoo.com
Sat Apr 19 23:31:39 CEST 2014



________________________________
> From: Vipul Sharma <vipul.sharma20 at gmail.com>
>To: tutor at python.org 
>Sent: Saturday, April 19, 2014 10:48 PM
>Subject: [Tutor]  equality check difference
> 
>
>
>Hello,
>
>
>Suppose we want some block of code to be executed when both 'a' and 'b' are equal to say 5. Then we can write like :
>
>
>if a == 5 and b == 5:
>    # do something
>
>
>But a few days ago, I just involuntarily wrote a similar condition check as :
>
>
>if a == b and b == 5:
>    # do something 
>
>
>which made me think, is there any difference between the two ?
>
>
>Is there any difference, any difference in the process of evaluation or execution ? and also which one is the better ?
>
>
>I think this is a general programming question and not specifically for python.
>
>
>P.S. : Newbie here :)

I used timeit and it does not seem to make a big difference. The dis module could help give insight what Python is doing behind the scenes (I am not so familiar with that module).


$ipython
Python 2.7.3 (default, Feb 27 2014, 19:39:10) 
Type "copyright", "credits" or "license" for more information.

IPython 0.13.1 -- An enhanced Interactive Python.


In [1]: a, b = 1, 2

In [2]: %timeit if a == 5 and b == 5: pass
1000000 loops, best of 3: 1.1 us per loop

In [3]: %timeit if a == b and b == 5: pass
1000000 loops, best of 3: 1.26 us per loop


In [4]: %timeit if a == b == 5: pass
100000 loops, best of 3: 1.97 us per loop


More information about the Tutor mailing list