+ 2
Why it is giving me the index number True (boolean value)is 0 when it is actually 4 in this list?? (But for False it is correct)
list = [1, 2.30, ['bye', 2], 'hi', True] for l in list: print(l, 'index number:', list.index(l), 'Data Type:', type(l)) https://code.sololearn.com/cgFvqZdiHFAN/?ref=app
3 ответов
+ 3
1 is considered equal to True (print(1 == True) returns True). So as the first element is 1, it takes that to be the first index of True. If you change 1 to 2, it will show True has index 4.
+ 9
This is how .index works. It just seeks for the first occurrence of its argument.
In most contexts, True is evaluated as 1 (and False as 0). In Python bool inherits from int and follows this pattern, too. So it's actually 1 that triggers .index to return the result that it has "found" True :)
+ 2
Russ got it. Thanks ☺