Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Binary Search in Python

Binary Search in Python

Posted on February 13, 2025February 13, 2025 By Rishabh saini No Comments on Binary Search in Python

Binary Search in Python

Introduction

Searching is a fundamental operation in computer science, and binary search is one of the most efficient algorithms for finding an element in a sorted list. Suppose we have a list of a thousand elements, and we need to determine the index position of a specific element—binary search allows us to find it quickly.

Among various searching algorithms, binary search stands out due to its efficiency and widespread use in real-world applications. However, the list must be sorted before applying the binary search algorithm. The items must be sorted first if they aren’t already.

Let’s explore the concept of binary search in detail.

Complete Python Course with Advance topics:-Click here

Concept of Binary Search

The divide and conquer strategy is used in binary search. There are two ways to implement it:

  1. Recursive Method
  2. Iterative Method

Until the element is located, the recursive approach calls a function repeatedly. In contrast, the iterative method uses a loop to iterate through the list until the element is located.

Binary search is much faster than linear search since it doesn’t check each index sequentially. Instead, it narrows the search space by half in each step, making it significantly more efficient.

Steps to Implement Binary Search

Let’s assume we have a sorted list and we want to find the index position of 45:

list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45

We set two pointers:

  • low → Points to the smallest index
  • high → Points to the highest index

Then, we calculate the middle index:

mid = (low + high) // 2

Here, low = 0 and high = 6:

mid = (0 + 6) // 2
mid = 3

We compare list1[mid] with n. If it matches, we return mid. Otherwise:

  • If n is greater than list1[mid], we search in the right half.
  • If n is smaller than list1[mid], we search in the left half.

This process repeats until we find the element or determine that it is not present in the list.

Implementing Binary Search in Python

Iterative Method

Below is the Python implementation using an iterative approach:

# Iterative Binary Search in Python
def binary_search(list1, n):  
    low = 0  
    high = len(list1) - 1  
    
    while low <= high:  
        mid = (low + high) // 2  
        
        # If element is present at mid
        if list1[mid] < n:  
            low = mid + 1  
        elif list1[mid] > n:  
            high = mid - 1  
        else:  
            return mid  
    return -1  

# Example usage:
list1 = [12, 24, 32, 39, 45, 50, 54]  
n = 45  
result = binary_search(list1, n)  

if result != -1:  
    print("Element is present at index", result)  
else:  
    print("Element is not present in list1")  

Output:

Element is present at index 4

Explanation:

  • A sorted list and a target number are passed to the binary_search() function.
  • The search space is tracked by two pointers, one high and one low.
  • Until low exceeds high, the while loop keeps going.
  • We return the index of the middle element if it matches n.
  • We update low if n exceeds the middle element.
  • We update high if n is less than the middle element.
  • We return -1 if n cannot be found.

Recursive Binary Search

Recursion can also be used to implement binary search:

# Recursive Binary Search in Python
def binary_search_recursive(list1, low, high, n):
    if low <= high:
        mid = (low + high) // 2
        
        if list1[mid] == n:
            return mid
        elif list1[mid] > n:
            return binary_search_recursive(list1, low, mid - 1, n)
        else:
            return binary_search_recursive(list1, mid + 1, high, n)
    else:
        return -1

# Example usage:
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 32
res = binary_search_recursive(list1, 0, len(list1) - 1, n)

if res != -1:
    print("Element is present at index", res)
else:
    print("Element is not present in list1")

Output:

Element is present at index 2

Explanation:

  • The recursive function keeps calling itself with updated values of low and high.
  • If the middle value equals n, the search ends.
  • If n is less than the middle value, the function is called recursively for the left half.
  • If n is greater than the middle value, the function is called recursively for the right half.
  • If low exceeds high, the function returns -1, indicating the element is not found.

Complexity Analysis

CaseTime Complexity
Best CaseO(1)
Average CaseO(log n)
Worst CaseO(log n)

Why is Binary Search Efficient?

  • Unlike linear search (O(n)), binary search reduces the search space by half at each step.
  • This makes it ideal for large datasets.
  • Works best on sorted lists.

Download New Real Time Projects :-Click here
Complete Advance AI topics:- CLICK HERE

Conclusion

Finding an element in a sorted list can be done quickly and effectively with binary search. It eliminates unnecessary comparisons, making it much faster than linear search. We explored both iterative and recursive implementations in Python.

By understanding and implementing binary search, programmers can optimize search operations, making their applications run faster and more efficiently.

This tutorial was brought to you by UpdateGadh, your go-to platform for the latest programming insights and tutorials.


binary search in python with example
binary search in python using for loop
binary search in python inbuilt
binary search in python using list
binary search in c
binary search in python without function
binary search in python w3schools
Binary Search in Python algorithm
Binary Search in Python

Post Views: 394
Python Interview Question Tags:binary search, binary search algorithm, binary search algorithm in python, binary search algorithm python, binary search algorithm using python, binary search in python, binary search program, binary search python, binary search tree, binary search tree python, binary search trees, linear search, Python, python binary search, python binary search algorithm, python binary search implementation, python binary search tree, python binary serach

Post navigation

Previous Post: E-Commerce Website Project Using Django with Source Code
Next Post: SQL INSERT Multiple Rows: A Time-Saving Technique

More Related Articles

Stack in Python Stack in Python – A Complete Guide Python Interview Question
Queue in Python Queue in Python Python Interview Question
Python vs Scala Python vs Scala Python Interview Question

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. How to Install Python on Windows: A Step-by-Step Guide
  2. How to Run Python Program: A Comprehensive Guide for Python Programmers
  3. How to Append Elements to a List in Python
  4. How to Declare a Global Variable in Python
  5. How to Clear the Python Shell
  6. How to Print Patterns in Python

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,612)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,210)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,866)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme