Skip to content

TypeError in bisect when called with key argument #117848

Closed

Description

@c-m-m-kobayashi

Bug report

Bug description:

bisect functions raise TypeError when called with key argument.
Here is a minimum code to reproduce the issue:

import bisect
import operator

a = [('one', 1), ('two', 2)]
print(bisect.bisect(a, ('one', 1), key=operator.itemgetter(0)))

This results in the following error:

Traceback (most recent call last):
  File "/path/to/bisect_test.py", line 5, in <module>
    print(bisect.bisect(a, ('one', 1), key=operator.itemgetter(0)))
          ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: '<' not supported between instances of 'tuple' and 'str'

It seems that picking an item in a tuple has a problem.

CPython versions tested on:

3.12

Operating systems tested on:

macOS

Activity

  1. added
    type-bug
    on Apr 13, 2024
  2. nineteendo commented on Apr 13, 2024

    @nineteendo
    Contributor

    You need to apply key() to the element:

    key=operator.itemgetter(0)
    print(bisect.bisect(a, key(('one', 1)), key=key))
  3. nineteendo commented on Apr 13, 2024

    @nineteendo
    Contributor
  4. nineteendo commented on Apr 13, 2024

    @nineteendo
    Contributor

    @AlexWaygood, could you close this? This works as intended. Sorry for the ping.

  5. c-m-m-kobayashi commented on Apr 13, 2024

    @c-m-m-kobayashi
    Author

    @nineteendo Thank you for your comment.
    Now I understand that giving the field to be compared is better than the entire record in bisect search.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions