DEV Community

Cover image for bisect module and methods(python)
\144\150\162\165\166(dhruv)
\144\150\162\165\166(dhruv)

Posted on • Edited on

1 1

bisect module and methods(python)

The bisect module is written in python and here is the source code
What it does?
The bisect module in Python provides support for maintaining a list in sorted order without having to sort the list after each insertion. It uses a binary search algorithm to find the insertion point for a given element in a sorted list, which is more efficient than linear search.

Key functions provided by the bisect module:

  • bisect.bisect_left(list, num, beg, end): This function returns the sorted list after inserting the number in the appropriate position. If the element already exists, then the element is inserted at the leftmost possible position. import bisect
list = [1, 3, 4, 4, 6, 7]
bisect.bisect_left(list, 5)
print(list)  # Output: [4]
Enter fullscreen mode Exit fullscreen mode
  • bisect.bisect_right(list, num, beg, end): This function works similar to bisect_left(), but if the element already exists, then the rightmost position is returned. bisect.bisect() is an alias for bisect_right(). import bisect
list = [1, 3, 4, 4, 4, 6, 7]
print(bisect.bisect_right(list, 4))  # Output: 5
Enter fullscreen mode Exit fullscreen mode
  • bisect.insort_left(list, num, beg, end): This function returns the sorted list after inserting the number in the appropriate position. If the element already exists, then the element is inserted at the leftmost possible position.
import bisect

list = [1, 3, 4, 4, 6, 7]
bisect.insort_left(list, 5)
print(list)  # Output: [1, 3, 4, 4, 5, 6, 7]

Enter fullscreen mode Exit fullscreen mode
  • bisect.insort_right(list, num, beg, end): This function works similar to insort_left(), but if the element already exists, then the element is inserted at the rightmost possible position. bisect.insort() is an alias for insort_right().
import bisect

list = [1, 3, 4, 4, 6, 7]
bisect.insort_right(list, 4)
print(list)  # Output: [1, 3, 4, 4, 4, 6, 7]

Enter fullscreen mode Exit fullscreen mode

In all these functions, beg and end are optional arguments specifying the range in which to search for the insertion point. If omitted, the entire list is used.

If you have any feedback, then you can DM me on Twitter or Linkedin.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more