Python Forum
IndexError: list index out of range
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IndexError: list index out of range
#1
please help me. i am unable to understand IndexError.

def binarySearch (arr,first,last,element):
    mid = first+last//2
    print("Value of index ",mid)
    print("Value of element ",arr[mid])
    if last>=first:
        if(element==arr[mid]):
            print("element",element,"found at location ",mid)
        else:
            if(element>arr[mid]):
                return binarySearch(arr,mid+1,last,element)
            else:
                return binarySearch(arr,first,mid-1,element)
    else:
        print("Element is not present in array")
    
arr = [int(x) for x in input("Enter list of element:").split(',')]
element=int(input("Enter search element:"))
binarySearch(arr,0,len(arr)-1,element)
==================== RESTART: C:/python/program/binary.py ====================
Enter list of element:2,3,4,5,6
Enter search element:2
Value of index 2
Value of element 4
Value of index 0
Value of element 2
element 2 found at location 0
>>>
==================== RESTART: C:/python/program/binary.py ====================
Enter list of element:2,3,4,5,6
Enter search element:3
Value of index 2
Value of element 4
Value of index 0
Value of element 2
Value of index 1
Value of element 3
element 3 found at location 1
>>>
==================== RESTART: C:/python/program/binary.py ====================
Enter list of element:2,3,4,5,6
Enter search element:3
Value of index 2
Value of element 4
Value of index 0
Value of element 2
Value of index 1
Value of element 3
element 3 found at location 1
>>>
==================== RESTART: C:/python/program/binary.py ====================
Enter list of element:2,3,4,5,6
Enter search element:5
Value of index 2
Value of element 4
Value of index 5
Traceback (most recent call last):
File "C:/python/program/binary.py", line 18, in <module>
binarySearch(arr,0,len(arr)-1,element)
File "C:/python/program/binary.py", line 10, in binarySearch
return binarySearch(arr,mid+1,last,element)
File "C:/python/program/binary.py", line 4, in binarySearch
print("Value of element ",arr[mid])
IndexError: list index out of range
>>>
==================== RESTART: C:/python/program/binary.py ====================
Enter list of element:2,3,4,5,6
Enter search element:6
Value of index 2
Value of element 4
Value of index 5
Traceback (most recent call last):
File "C:/python/program/binary.py", line 18, in <module>
binarySearch(arr,0,len(arr)-1,element)
File "C:/python/program/binary.py", line 10, in binarySearch
return binarySearch(arr,mid+1,last,element)
File "C:/python/program/binary.py", line 4, in binarySearch
print("Value of element ",arr[mid])
IndexError: list index out of range
Reply
#2
(Sep-02-2017, 07:00 AM)rajeev1729 Wrote: please help me. i am unable to understand IndexError.

mid = first+last//2

You are getting that error due to logical a mistake. Read about the order of operation and operator precedence here.

Here's how this expression will be evaluated in python:
1- last is divided by 2 and only integer(//) is stored.
2- result from above step is added to first and stored in mid.

what you want is:
mid = (first+last)//2
Reply
#3
what hbknjr says is correct:

If you add one more statement to for routine and slight modification to print statements, the error becomes clear:
def binarySearch(arr, first, last, element):
    print('value of arr: {}'.format(arr))
    mid = first + last // 2
    print("Value of mid: {}".format(mid))
    print("Value of arr[mid]: {}".format(arr[mid]))
    if last >= first:
        if (element == arr[mid]):
            print("element", element, "found at location ", mid)
        else:
            if (element > arr[mid]):
                return binarySearch(arr, mid + 1, last, element)
            else:
                return binarySearch(arr, first, mid - 1, element)
    else:
        print("Element is not present in array")


arr = [int(x) for x in input("Enter list of element:").split(',')]
element = int(input("Enter search element:"))
binarySearch(arr, 0, len(arr) - 1, element)
first crash from your attempts:
inputs:
Output:
Enter list of element:2,3,4,5,6 Enter search element:5
results:
C:\Python36\python.exe M:/python/ProvingGround/newStuff/FindIndex1.py
Enter list of element:2,3,4,5,6
Enter search element:5
Output:
Traceback (most recent call last):   File "M:/python/ProvingGround/newStuff/FindIndex1.py", line 20, in <module>     binarySearch(arr, 0, len(arr) - 1, element)   File "M:/python/ProvingGround/newStuff/FindIndex1.py", line 11, in binarySearch     return binarySearch(arr, mid + 1, last, element)   File "M:/python/ProvingGround/newStuff/FindIndex1.py", line 5, in binarySearch     print("Value of arr[mid]: {}".format(arr[mid])) IndexError: list index out of range value of arr: [2, 3, 4, 5, 6] Value of mid: 2 Value of arr[mid]: 4 value of arr: [2, 3, 4, 5, 6] Value of mid: 5
You can see here that there is no element 5 ... remember index is 0 to 4
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  IndexError: index 10 is out of bounds for axis 0 with size 10 Mehboob 11 2,104 Sep-14-2023, 06:54 AM
Last Post: Mehboob
Thumbs Down I hate "List index out of range" Melen 20 3,319 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 6,361 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,913 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,349 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,442 May-03-2022, 01:39 PM
Last Post: Anldra12
  TypeError: list indices must be integers or slices, not range Anldra12 2 2,581 Apr-22-2022, 10:56 AM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,209 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,847 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,309 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020