

{"id":97859,"date":"2021-06-30T09:00:48","date_gmt":"2021-06-30T03:30:48","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=97859"},"modified":"2026-06-01T12:39:50","modified_gmt":"2026-06-01T07:09:50","slug":"binary-search-python-program","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/","title":{"rendered":"Binary Search in Python (Recursive and Iterative)"},"content":{"rendered":"<div class='__iawmlf-post-loop-links' style='display:none;' data-iawmlf-post-links='[{&quot;id&quot;:2550,&quot;href&quot;:&quot;https:\\\/\\\/drive.google.com\\\/file\\\/d\\\/1e4Yq4yJ40hEQkuMSxZk_TxoYYoOpg3N1\\\/view?usp=drive_link&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20260601071126\\\/https:\\\/\\\/drive.google.com\\\/file\\\/d\\\/1e4Yq4yJ40hEQkuMSxZk_TxoYYoOpg3N1\\\/view?usp=drive_link&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2026-06-02 06:59:58&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-05 14:57:33&quot;,&quot;http_code&quot;:200}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2026-06-05 14:57:33&quot;,&quot;http_code&quot;:200},&quot;process&quot;:&quot;done&quot;}]'><\/div>\n<p>Searching for an element\u2019s presence in a list is usually done using linear search and binary search. Linear search is time-consuming and memory expensive but is the simplest way to search for an element. On the other hand, Binary search is effective mainly due to the reduction of list dimension with each recursive function call or iteration. A practical implementation of binary search is autocompletion.<\/p>\n<h3>Python Binary Search Algorithm:<\/h3>\n<p>The objective of this project is to create a simple python program to implement binary search. It can be implemented in two ways: recursive (function calls) and iterative.<\/p>\n<h3>Project Prerequisites:<\/h3>\n<p>The project uses loops and functions to implement the search function. Hence good knowledge of python loops and function calls is sufficient to understand the code flow.<\/p>\n<h3>Download Binary Search Algorithm Python Code:<\/h3>\n<p>Please download the source code python binary search algorithm from the following link: <a href=\"https:\/\/drive.google.com\/file\/d\/1e4Yq4yJ40hEQkuMSxZk_TxoYYoOpg3N1\/view?usp=drive_link\"><strong>Binary Search Python Code<\/strong><\/a><\/p>\n<h3>Project File Structure:<\/h3>\n<p>Let\u2019s have a look at the steps to build binary search python project:<\/p>\n<p>1. Recursive approach<\/p>\n<ul>\n<li>Function definition<\/li>\n<li>Read inputs, sort and call function<\/li>\n<\/ul>\n<p>2. Iterative approach<\/p>\n<ul>\n<li>Read inputs and sort<\/li>\n<li>Loop for binary search<\/li>\n<\/ul>\n<p>Let us look at the implementation in detail.<\/p>\n<h4>1. Recursive approach<\/h4>\n<p><strong>I. Function definition<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#DataFlair Guide for Binary Search\r\n#RECURSIVE FUNCTION CALL BASED APPROACH\r\n#Function to search element in list\r\ndef binary_search(start,end,int_list,target):\r\n  #Condition to check if element is not present \r\n  if start&lt;=end:\r\n     mid = (start+end) \/\/ 2\r\n \r\n     #Check if mid element is the target element\r\n     if int_list[mid] == target:\r\n       return mid +1\r\n \r\n     #If not, check if lesser than mid element\r\n     #Change range to start to mid-1, since less than mid\r\n     elif target &lt; int_list[mid]:\r\n       return binary_search(start,mid-1,int_list,target)\r\n \r\n     #Check if lesser than mid element\r\n     #Change range to mid+1 to end, since greater than mid\r\n     elif target &gt; int_list[mid]:\r\n       return binary_search(mid+1,end,int_list,target)\r\n  else:\r\n     return -1\r\n<\/pre>\n<p><strong>Code Explanation:<\/strong><\/p>\n<ul>\n<li><strong>def binary_search(start,end,int_list,target):<\/strong> Declare and define the function binary search with parameters: start, end, list of elements and target element<\/li>\n<li><strong>start&lt;=end:<\/strong> This condition is necessary to avoid an out_of_index_error and satisfies the condition when an element is not present in a list.<\/li>\n<li><strong>Test conditions:<\/strong> If the target is the middle element of the list, the position is returned, else it is checked if less than the middle element. Upon satisfying this condition, the function is called with a change in the lower and upper bounds being start and mid-1 respectively. Similarly, for the case of the target element being greater than the middle element, the bounds are updated to mid+1 and end.<\/li>\n<li><strong>Return value:<\/strong> The binary search python function return position, if the element is found and -1 otherwise.<\/li>\n<\/ul>\n<p><strong>II. Read inputs and call function:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">length = int(input(\"Enter length of list: \"))\r\nint_list = []\r\n#Read elements of list\r\nfor i in range(length):\r\n element =  int(input(\"Enter element: \"))\r\n int_list.append(element)\r\n#Sort the list\r\nint_list=sorted(int_list)\r\nprint(int_list)\r\n#Read target element to be found\r\ntarget = int(input(\"Enter target element: \"))\r\nposition = binary_search(0,length-1,int_list,target)\r\nif position == -1:\r\n   print('Element not in list')\r\nelse:\r\n   print(\"Element found at position: \"+ str(position))\r\n<\/pre>\n<p><strong>Code Explanation:<\/strong><\/p>\n<ul>\n<li><strong>Inputs:<\/strong> Read the list length from the user and the elements of the list. Append the elements to the list<\/li>\n<li><strong>sorted(int_list):<\/strong> A prerequisite for binary search is to have a sorted list. Hence using sorted(), we sort the list<\/li>\n<li><strong>Function call:<\/strong> The inputs are passed to the function binary_search. The value returned is printed.<\/li>\n<\/ul>\n<h4>2. Iterative Approach:<\/h4>\n<p>Now, let&#8217;s discuss python binary search iterative approach:<\/p>\n<p><strong>I. Read inputs and sort the list:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#DataFlair Guide for Python Binary Search\r\n#ITERATIVE APPROACH\r\n#Read length of list from user\r\nlength = int(input(\"Enter length of list: \"))\r\nint_list = []\r\n#Read elements of list\r\nfor i in range(length):\r\n element =  int(input(\"Enter element: \"))\r\n int_list.append(element)\r\n#Sort the list\r\nint_list=sorted(int_list)\r\nprint(int_list)\r\n#Read target element to be found\r\ntarget = int(input(\"Enter target element: \"))<\/pre>\n<p><strong>Code explanation:<\/strong><\/p>\n<ul>\n<li><strong>Inputs:<\/strong> Read the list length from the user and using a for loop, read the elements of the list. Append the elements to the list<\/li>\n<li><strong>sorted(int_list):<\/strong> Sort the list for binary search<\/li>\n<\/ul>\n<p><strong>II. Loop for binary search<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#Define variables\r\nstart = 0\r\nend = length-1\r\nposition = -1\r\n \r\nwhile(start&lt;=end):\r\n mid = (start+end) \/\/ 2 \r\n if int_list[mid] == target:\r\n   position = mid\r\n   break\r\n #If not, check if lesser than mid element\r\n #Change range to start to mid-1, since less than mid\r\n elif target &lt; int_list[mid]:\r\n   end = mid-1\r\n #Check if lesser than mid element\r\n #Change range to mid+1 to end, since greater than mid\r\n elif target &gt; int_list[mid]:\r\n   start = mid+1\r\n \r\nif position == -1:\r\n   print('Element not in list')\r\nelse:\r\n   print(\"Element found at position: \"+ str(position+1))\r\n<\/pre>\n<p><strong>Code Explanation:<\/strong><\/p>\n<ul>\n<li><strong>Define variables:<\/strong> Define variables start, and end position. Position is set to -1 initially<\/li>\n<li><strong>While loop:<\/strong> The terminating condition for the while loop is \u2018start&lt;=end\u2019. Inside the loop, check the target element with the middle element, and update the position variable. If lesser than middle element, update upper bound to middle-1 and in the case of greater than middle element, update start to middle +1.<\/li>\n<li><strong>Position condition:<\/strong> If position remains unchanged at -1, it indicates the element is not present in the list. If it is updated, then the position is printed.<\/li>\n<\/ul>\n<h3>Binary Search Python Output:<\/h3>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/binary-search-python-output.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97862\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/binary-search-python-output.png\" alt=\"binary search python output\" width=\"1366\" height=\"624\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/binary-search-python-output.png 1366w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/binary-search-python-output-768x351.png 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/binary-search-python-output-720x329.png 720w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/binary-search-python-output-520x238.png 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/binary-search-python-output-320x146.png 320w\" sizes=\"auto, (max-width: 1366px) 100vw, 1366px\" \/><\/a><\/p>\n<h3>Summary<\/h3>\n<p>We created a simple Binary Search Algorithm in Python. The python project covers both: an iterative approach using loops and recursive function calls using function.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Searching for an element\u2019s presence in a list is usually done using linear search and binary search. Linear search is time-consuming and memory expensive but is the simplest way to search for an element.&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":97863,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[24691,24690,24692,24693],"class_list":["post-97859","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-binary-search-python","tag-binary-search-python-program","tag-iterative-binary-search-python","tag-recursive-binary-search-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Binary Search in Python (Recursive and Iterative) - DataFlair<\/title>\n<meta name=\"description\" content=\"Python binary search algorithm - Create a python program for binary search using recursive as well as iterative approach.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Binary Search in Python (Recursive and Iterative) - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Python binary search algorithm - Create a python program for binary search using recursive as well as iterative approach.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-30T03:30:48+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-06-01T07:09:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/python-binary-search.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Binary Search in Python (Recursive and Iterative) - DataFlair","description":"Python binary search algorithm - Create a python program for binary search using recursive as well as iterative approach.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/","og_locale":"en_US","og_type":"article","og_title":"Binary Search in Python (Recursive and Iterative) - DataFlair","og_description":"Python binary search algorithm - Create a python program for binary search using recursive as well as iterative approach.","og_url":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2021-06-30T03:30:48+00:00","article_modified_time":"2026-06-01T07:09:50+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/python-binary-search.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Binary Search in Python (Recursive and Iterative)","datePublished":"2021-06-30T03:30:48+00:00","dateModified":"2026-06-01T07:09:50+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/"},"wordCount":597,"commentCount":1,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/python-binary-search.jpg","keywords":["binary search python","binary search python program","iterative binary search python","recursive binary search python"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/","url":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/","name":"Binary Search in Python (Recursive and Iterative) - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/python-binary-search.jpg","datePublished":"2021-06-30T03:30:48+00:00","dateModified":"2026-06-01T07:09:50+00:00","description":"Python binary search algorithm - Create a python program for binary search using recursive as well as iterative approach.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/binary-search-python-program\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/python-binary-search.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/06\/python-binary-search.jpg","width":1200,"height":628},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/binary-search-python-program\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Binary Search in Python (Recursive and Iterative)"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/97859","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=97859"}],"version-history":[{"count":4,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/97859\/revisions"}],"predecessor-version":[{"id":148627,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/97859\/revisions\/148627"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/97863"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=97859"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=97859"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=97859"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}