0

From Python docs:

list.index(x): Return the index in the list of the first item whose value is x. It is an error if there is no such item.

But, the following examples return these in the Python shell:

>>> [1, 2,True, 3, 'a', 4].index(True)
0
>>> [1, 2, 3, 'a', 4].index(True)
0

As you can see, it seems to be returning 0 even when True is not present in the list. This seems to be happening only when the parameter is True in list.index():

Does anyone know why?

Daniel Cook
  • 1,856
  • 8
  • 23
  • 28

2 Answers2

1

It's because True == 1:

>>> True == 1
True

So the result is in accordance with the documentation, i.e. the index of the first element that == True is returned. In this case, that's 1 at index 0.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

That's because :

>>> True == 1
True

list.index performs equality check, so, it returns the index 0 for you.

>>> lis = [1, 2,True, 3, 'a', 4]
>>> next(i for i, x in enumerate(lis) if x == True)
0
>>> lis = [1, 2, 3, 'a', 4]
>>> next(i for i, x in enumerate(lis) if x == True)
0

Related:

Is it Pythonic to use bools as ints?

Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Thank you, that clarified it for me. Though, yhy does True == 1 return True? I mean, it makes no sense because 1 and True are definitely not the same, do you know why they are apparently the same? – Daniel Cook Oct 20 '13 at 17:38
  • `True` and `1` are *exactly* the same. `True` is just `1` wearing a fancy suit. – kindall Oct 20 '13 at 19:52