Home > database >  IndexError: list index out of range when sorting list in Z-A order
IndexError: list index out of range when sorting list in Z-A order

Time:02-26

lst=['rocky','parkour','boy','is','a','zoo']
lst_sorted=[]
while len(lst)>0:
    for i in range(len(lst)):
        if(lst[i]==max(lst):
            lst_sorted.append(max(lst))
            lst.remove(max(lst))
print(lst_sorted)
print(lst)

Output:

Traceback (most recent call last):
  File "<string>", line 6, in <module>
IndexError: list index out of range

CodePudding user response:

lst=['rocky','parkour','boy','is','a','zoo']
lst_sorted=[]
while len(lst)>0:
            lst_sorted.append(max(lst))
            lst.remove(max(lst))
print("Revese sorted",lst_sorted)

CodePudding user response:

You're removing items from the list after you determine the 'range' of len(lst). So your shrinking the list as you go through it.

If it's easier, in python you can just do list(reversed(sorted(lst)))

lst = 'rocky', 'parkour', 'boy', 'is', 'a', 'zoo']
print(list(reversed(sorted(lst))))
# Output: ['zoo', 'rocky', 'parkour', 'is', 'boy', 'a']

--

In the comments IOT RnD wanted to understand his implementation better, so here's a quick explanation of how I'd figure it out if it were my code. Here's the original code, slightly modified to print debug important bits.

lst=['rocky','parkour','boy','is','a','zoo']
lst_sorted=[]
while len(lst)>0:
    to_iterate = list(range(len(lst)))
    print(f"Iterating over range {to_iterate}")
    for i in to_iterate:
        print(f"On {i}: {lst[i]}, comparing against {max(lst)}. lst={lst}")
        if lst[i]==max(lst):
            print(f"lst[i] == max(lst).  Adding to sorted list and removing from lst.")
            lst_sorted.append(max(lst))
            lst.remove(max(lst))
print(lst_sorted)
print(lst)

The output would look like this:

Iterating over range [0, 1, 2, 3, 4, 5]
On 0: rocky, comparing against zoo. lst=['rocky', 'parkour', 'boy', 'is', 'a', 'zoo']
On 1: parkour, comparing against zoo. lst=['rocky', 'parkour', 'boy', 'is', 'a', 'zoo']
On 2: boy, comparing against zoo. lst=['rocky', 'parkour', 'boy', 'is', 'a', 'zoo']
On 3: is, comparing against zoo. lst=['rocky', 'parkour', 'boy', 'is', 'a', 'zoo']
On 4: a, comparing against zoo. lst=['rocky', 'parkour', 'boy', 'is', 'a', 'zoo']
On 5: zoo, comparing against zoo. lst=['rocky', 'parkour', 'boy', 'is', 'a', 'zoo']
lst[i] == max(lst).  Adding to sorted list and removing from lst.
Iterating over range [0, 1, 2, 3, 4]
On 0: rocky, comparing against rocky. lst=['rocky', 'parkour', 'boy', 'is', 'a']
lst[i] == max(lst).  Adding to sorted list and removing from lst.
On 1: boy, comparing against parkour. lst=['parkour', 'boy', 'is', 'a']
On 2: is, comparing against parkour. lst=['parkour', 'boy', 'is', 'a']
On 3: a, comparing against parkour. lst=['parkour', 'boy', 'is', 'a']
Traceback (most recent call last):
  File "C:\Users\eddie\test.py", line 7, in <module>
    print(f"On {i}: {lst[i]}, comparing against {max(lst)}. lst={lst}")
IndexError: list index out of range

Looking at the output you can quickly see that you're shrinking the list 'lst' but you still have indices that point past the end of the array, so you get an error. you can fix this by 'break'ing after you remove, or reversing your iteration of range(len(lst)) so the indices are always valid, even in the face of a removal.

  • Related