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!

Major
  • 159
  • 1
  • 7
  • 2
    The key function must be passed as a named argument `key=...`. Otherwise it is treated as just another data argument. – John Gordon Aug 01 '22 at 04:03

1 Answers1

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
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31