0

I am trying to use Bisect to find where I should insert a new element.

The list to search is a list of lists. The inner list has two elements and I want to compare using the first element.

In the bisect function documentation, it says that the key function is supposed to take the element and get the value to compare. In this case, I am getting the first element of the list.

i = bisect.bisect([[1,2], [2,3], [3,4]], 4, lambda x: x[0])

I got the following error:

TypeError: 'function' object cannot be interpreted as an integer

I also tried to warp the item with a list but the problem persists

i = bisect.bisect([[1,2], [2,3], [3,4]], [4,5] , lambda x: x[0])

If I tried to remove the key function, it works if I warp the value by a list:

i = bisect.bisect([[1,2], [2,3], [3,4]], [4])
print(i)
> 3

However, I am still not sure why the key function is not working.

Any suggestions? Thanks in advance!

1
  • 2
    The key function must be passed as a named argument key=.... Otherwise it is treated as just another data argument. Commented Aug 1, 2022 at 4:03

1 Answer 1

1

As shown in the link you provided, the third argument of bisect is the left side of the search scope, not the key:

bisect.bisect(a, x, lo=0, hi=None, *, key=None)

To use key, use the keyword argument:

>>> bisect.bisect([[1,2], [2,3], [3,4]], 4, key=lambda x: x[0])
3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.