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 "", line 6, in IndexError: list index out of range
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']
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)