简体   繁体   中英

IndexError: list index out of range with a while loop

I've been trying to fix this but the same error message came up every time:

while number_list[i] <= number_list[j]:

IndexError: list index out of range

I've searched for the same type of bug, but not very similar cases found.

Here it is the head program (orders the numbers of my list, from the little one to the bigger):

    number_list=[]

list_lenght=int(input("List lenght: "))

while len(number_list)<list_lenght:
    item=input("Enter new item to the list:")
    number_list.append(item)
    print(number_list)

print("That's your number list: ",number_list)

number_list_final=[]

def order_number_list(number_list):
    i=0
    j=1
    while (j)<=(len(number_list)-1):
        while number_list[i]<=number_list[j]:
            j=j+1
        i=j
        j=i+1
    final_item=number_list[i]
    number_list_final.append(final_item)`
    del number_list[i] 
    order_number_list(number_list)

order_number_list(number_list)
print(number_list_final)

I know this is about iterating with the list while modifying it, but no idea how to fix it.

Can anyone help me to debug this, or give me some tips?

Thank you!

If I understand you correctly, you're trying to sort a list of numbers. There's a built-in Python method for this, that has been optimized for ages to be fast and use minimal memory, it's called sorted .

Instead of running order_number_list , try:

print(sorted(number_list))

If this is some kind of homework, and you're not allowed to use the built-in sorted , for educational purposes I would recommend you to use a sorting algorithm called bubble sort, more information here - Bubble Sort Homework .

Updating your code to include a couple of print statements shows that the j increases to past the length of the list. Then the "while number_list[i]<=number_list[j]:" no longer can be completed as there is no "number_list[j]" for the j value.

number_list=[1,2,3,4,5]

list_lenght=5
#=int(input("List lenght: "))

#while len(number_list)<list_lenght:
#    item=input("Enter new item to the list:")
#    number_list.append(item)
#    print(number_list)

print("That's your number list: ",number_list)

number_list_final=[]

def order_number_list(number_list):
    i=0
    j=1
    while (j)<=(len(number_list)):
        while number_list[i]<=number_list[j]:
            print (j)
            print (i)
            j=j+1
        i=j
        j=i+1
    final_item=number_list[i]
    number_list_final.append(final_item)
    del number_list[i] 
    order_number_list(number_list)

order_number_list(number_list)
print(number_list_final)

This outputs :

That's your number list:  [1, 2, 3, 4, 5]
1
0
2
0
3
0
4
0
Traceback (most recent call last):
  File "C:/Python3/numberlist.py", line 30, in <module>
    order_number_list(number_list)
  File "C:/Python3/numberlist.py", line 19, in order_number_list
    while number_list[i]<=number_list[j]:
IndexError: list index out of range

The code is falling over once j is 5 for this example, it is trying to compare to a number that doesnt exist

number_list=[]

list_lenght=int(input("List length: "))

while len(number_list)<list_lenght:
    item=input("Enter new item to the list:")
    number_list.append(int(item))
    print(number_list)

print("That's your number list: ",number_list)

number_list_final=[]

def order_number_list(number_list):
    current_low = ["number"]
    current_low[0] = number_list[0]
    x = 1
    current_low_pos = 0
    while x < len(number_list):
        if current_low[0] > number_list[x]:
            current_low[0] = number_list[x]
            current_low_pos = x
        x = x + 1
    del number_list[current_low_pos]

    if number_list == []:
        remaining_list = []
    else:
        remaining_list = order_number_list(number_list)

    return (current_low + remaining_list)
number_list_final = order_number_list(number_list)
print(number_list_final)

This is code that has been clarified and corrected. j was not working right, as other answers have pointed out.

number_list.append(item)

needed to be changed to:

number_list.append(int(item))

because you cant compare strings with the '<' operator.

I also added a return statement, added this line of code:

number_list_final = order_number_list(number_list)

because your final print statement would print an empty list because:

order_number_list(number_list)

doesn't change the variable number_list_final.

I changed some of the function code to simply and make it more readable.

It also explicitly sets the current lowest item to be the first, and changes that if a lower item is found later on.

Hope this helps, let me know if you have any questions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM