This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: counterintuitive behavior of list.index with boolean values
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.4
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ezio.melotti, wolma
Priority: normal Keywords:

Created on 2014-07-16 21:43 by wolma, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (5)
msg223284 - (view) Author: Wolfgang Maier (wolma) * Date: 2014-07-16 21:43
>>> l = [False, True]
>>> l.index(True)
1
>>> l.index(False)
0

good, but:

>>> l = ['a', '', {}, 2.7, 1, 0, False, True]
>>> l.index(True)
4
>>> l.index(False)
5

Apparently, True and False get converted to int in comparisons to ints.
I would expect items to be compared either by:

a) object identity or
b) __eq__

but not this inconsistently.

Best,
Wolfgang
msg223285 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2014-07-16 21:51
It's using __eq__:
>>> l = [3, 1.0, 5, True, 7, 1]
>>> l.index(1)
1
>>> l.index(True)
1
>>> l.index(1.0)
1
>>> True == 1 == 1.0
True
msg223286 - (view) Author: Wolfgang Maier (wolma) * Date: 2014-07-16 21:55
No, it's not that simple and I don't think this should be closed:

In my example:
>>> l = ['a', '', {}, 2.7, 1, 0, False, True]
>>> l.index(True)
4
>>> l.index(False)
5

if using __eq__ consistently, you'd expect the first call to return 0 and the second 1 (since the empty string evaluates to False).
msg223287 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2014-07-16 22:04
'a' evaluates to true, but it's not equal to True:
  >>> bool('a')
  True
  >>> 'a' == True
  False
but 1 and True are equal (for historical reasons):
  >>> 1 == True
  True

Similarly '' evaluates to false, but it's not equal to False:
  >>> bool('')
  False
  >>> '' == False
  False
whereas 0 is equal to False:
  >>> 0 == False
  True
msg223288 - (view) Author: Wolfgang Maier (wolma) * Date: 2014-07-16 22:09
Right, forgot about that.

The consequence for the example is still far from satisfying, I think, but you can't change it without breaking compatibility then.

Thanks for the quick reply,
Wolfgang
History
Date User Action Args
2022-04-11 14:58:06adminsetgithub: 66192
2014-07-16 22:09:44wolmasetmessages: + msg223288
2014-07-16 22:04:15ezio.melottisetmessages: + msg223287
2014-07-16 21:55:22wolmasetmessages: + msg223286
2014-07-16 21:51:55ezio.melottisetstatus: open -> closed

nosy: + ezio.melotti
messages: + msg223285

resolution: not a bug
stage: resolved
2014-07-16 21:43:37wolmacreate