It’s to do with the recursion as the list gets shortened.

If the middle value comes after the search term, the function recurses over the left half, else the right. Check again for relativity, recurse half again, and so on. We can see it only takes about half a dozen recursions.

Feed in a range of numbers to see a clearer picture…

binary_search(range(1000),679)

Checking the bookshelf and finding: 0
Checking the bookshelf and finding: 501
Checking the bookshelf and finding: 501
Checking the bookshelf and finding: 626
Checking the bookshelf and finding: 626
Checking the bookshelf and finding: 658
Checking the bookshelf and finding: 674
Checking the bookshelf and finding: 674
Checking the bookshelf and finding: 678
Found the book: 679

May I suggest replacing the line print("Checking the bookshelf and finding: {0}".format(lst[0]))
with print("Checking the bookshelf and finding: {0}".format(lst[len(lst) // 2]))

That way the program displays the book in the middle of the selection, which seems more relevant to me than the book at the start of the selection.

def binary_search(lst, search_val):
if len(lst) == 0:
print("Book is not on the shelf!")
return
print("Checking the bookshelf and finding: {0}".format(lst[0]))
mid = len(lst) // 2
if lst[mid] == search_val:
print("\nFound the book: {0}\n\n\n\n\n\n".format(search_val))
return
elif lst[mid] > search_val:
binary_search(lst[:mid], search_val)
else:
binary_search(lst[(mid + 1):], search_val)

I wrote binary_search(bookshelf, "Do Androids Dream of Electric Sheep?") in my code as the exercise explains. Unfortunately, when I run the code I do not see the book found.

This is what is shown:

Checking the bookshelf and finding: 1st To Die
Checking the bookshelf and finding: 1st To Die
Checking the bookshelf and finding: 1st To Die
Checking the bookshelf and finding: Cat’s Cradle
Checking the bookshelf and finding: Cat’s Cradle
Checking the bookshelf and finding: Defending Jacob

Found the book: Do Androids Dream of Electric Sheep?

So, where is “Do Androids Dream of Electric Sheep?”

This will come up in the lessons, at some point, if it hasn’t already. It’s a concept known as recursion. Notice that the calls are inside a conditional, of which one is the base case (in this case, search_val is found) and the other two are recursive cases.

If you have the time to segue, look up the topic of recursion to gain a greater understanding. There are even a few examples here in the forums that you may glean something from.

I copy and paste this code in vs code I got a problem with inconsistent use of tabs and spaces in indentation in line 23 and 24. How can I fix this problem?