python / cpython

The Python programming language
https://www.python.org
Other
63.41k stars 30.36k forks source link

The index method of the tuple is incorrect #124268

Closed liuhuang2099 closed 1 month ago

liuhuang2099 commented 1 month ago

Bug report

Bug description:

# The result is 0? why? I think it should be three

tupleTest = (1,5,'gg',True,'kk',False) print(tupleTest.index(True))

CPython versions tested on:

3.12

Operating systems tested on:

Windows

skirpichev commented 1 month ago

That's because 1==True:)

skirpichev commented 1 month ago

The algorithm roughly equal to:

def index(tup, val):
    for i, el in enumerate(tup):
        if el == val:
            return i
    raise ValueError

Probably this could be closed.

liuhuang2099 commented 1 month ago

The algorithm roughly equal to:

def index(tup, val):
    for i, el in enumerate(tup):
        if el == val:
            return i
    raise ValueError

Probably this could be closed. Well, thank you! you gave a good idea, I can use enumeration method to match for i,j in enumerate(tupleTest): print(i,j)

Returned result: 0 1 1 5 2 gg 3 True 4 kk 5 False

skirpichev commented 1 month ago

Ok, I'm closing this. I think that documentation is clear, that for membership tests (x in s) or in s.index(x) - tested equality of elements.

Perhaps, next time you could ask first on https://discuss.python.org/c/help/7, if you find something surprising in the language like that and docs doesn't help you.

@ZeroIntensity for second look

ZeroIntensity commented 1 month ago

Yeah, index uses the C equivalent of an == comparison internally, so this is expected. Thank you, Sergey!