[Tutor] comparison bug in python (or do I not get it?)

Hans Fangohr h.fangohr at soton.ac.uk
Fri Feb 29 13:29:42 CET 2008


Dear Python folks,

here is a sequence of commands (ipython) that lead to a question. 
See my comments after leading '#':

In [1]: 2 in [1,2,3]
Out[1]: True

#nothing special here, of course 2 is in the list.

In [2]: 2 in [1,2,3] == True
Out[2]: False

#This is somewhat surprising, as one would hope that '2 in [1,2,3]'
#evaluates to 'True', and then we expect 'True'=='True' to hold.
#However, maybe it is an issue of operator precedence. Let's add parenthesis:

In [3]: (2 in [1,2,3]) == True
Out[3]: True

#Okay, so this does what we expect. 
#However, if it is an issue of operator precedence, then what is the 
#operation that is carried out at prompt [2] above?
#
#Presumably, we work out

In [4]: [1,2,3] == True
Out[4]: False

#which is false. So effectively, The statement at [2] seems to boil down to

In [5]: 2 in False
   ---------------------------------------------------------------------------
   exceptions.TypeError                                 Traceback (most recent call last)

   /Volumes/Minmax250a/Users2/fangohr/<console>

   TypeError: iterable argument required

But this throws an error! And so does the full expression (with paranthesis):

In [6]: 2 in ([1,2,3] == True)
   ---------------------------------------------------------------------------
   exceptions.TypeError                                 Traceback (most recent call last)

   /Volumes/Minmax250a/Users2/fangohr/<console>

   TypeError: iterable argument required



So what is the story here? In my view, the statement in line [2]
should either produce True (as in [3]), or throw an error (as in [6]).

Why does [2] return False? Would people agree that this is a bug?


Thank you for your time,

Hans



PS I have tested this with Python 2.4, and Python 2.5 (on debian etch)


--
Hans Fangohr

School of Engineering Sciences 
University of Southampton 
Phone: +44 (0) 238059 8345

Email: fangohr at soton.ac.uk
http://www.soton.ac.uk/~fangohr






More information about the Tutor mailing list