Issue 21993: counterintuitive behavior of list.index with boolean values (original) (raw)

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:06 admin set github: 66192
2014-07-16 22:09:44 wolma set messages: +
2014-07-16 22:04:15 ezio.melotti set messages: +
2014-07-16 21:55:22 wolma set messages: +
2014-07-16 21:51:55 ezio.melotti set status: open -> closednosy: + ezio.melottimessages: + resolution: not a bugstage: resolved
2014-07-16 21:43:37 wolma create