Skip to content

builtin min() returns wrong result in the following use case where its key argument is specified #135879

Closed as not planned
@redihokuto

Description

@redihokuto

Bug report

Bug description:

def stem(name:str) -> str:
    idx = min(name.find('-'), name.find('^'), key=lambda x: x if x >= 0 else len(name))
    return name[:idx]

#   The result should be always ABC, but this one fails
#   In the min() calling both find() returns -1 that is going to be substituted with 3 by the lamba
#   So that we should get min(3,3), instead we get -1
print(stem('ABC'))

print(stem('ABC-DE'))
print(stem('ABC-DE^FGH'))
print(stem('ABC-DE^FGH^JKL'))
print(stem('ABC^FGH^JKL'))
print(stem('ABC^FGH'))

According to the docs the key function is applied to each element. So that on the first case we should arrive to min(3,3). I was expecting 3, instead I get -1.

The same result comes out if we pass a collection (a tuple in this case):

min((name.find('-'), name.find('^')), key=lambda x: x if x >= 0 else len(name))

Thanks

CPython versions tested on:

3.13

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions