Reputation: 155
This is the question of the exercise: write a function that checks if a list is sorted in ascending order.
def ascending(lst):
for k in range(0,len(lst)):
if lst[k] < lst[k+1]:
print('Ok')
else:
print('NOk, the number ' + str(lst[k]) + ' is greater than his next ' + str(lst[k+1]))
return 'Bye!'
lst = [1,3,2,4,5]
print(ascending(lst))
I expect the output: Ok, Ok, NOk the number 3 is greather than his next 2, Ok ... and I get it but, at the very end of the problem, the error message is obviously "IndexError: list index out of range". I understood that the problem is at the end of the if statement because for k = 4, k+1 = 5 (out of range) but I don't know how to solve it.
Upvotes: 2
Views: 433
Reputation: 73470
The easiest:
def ascending(lst):
lst == sorted(lst)
But this is log-linear and does not short-circuit. Better:
def ascending(lst):
return all(a <= b for a, b in zip(lst, lst[1:]))
or in Python >= 3.10:
from itertools import pairwise
def ascending(lst):
return all(a <= b for a, b in pairwise(lst))
Upvotes: 0
Reputation: 9711
If your task is as simple as 'Test if a list is sorted in ascending order'; then how about a simple function like:
def issorted(lst):
return lst == sorted(lst)
print('Is sorted: ', issorted([5, 4, 1, 2]))
print('Is sorted: ', issorted([1, 2, 3, 4]))
print('Is sorted: ', issorted(['a', 'b', 'd', 'c']))
print('Is sorted: ', issorted(['w', 'x', 'y', 'z']))
Which outputs:
Is sorted: False
Is sorted: True
Is sorted: False
Is sorted: True
Upvotes: 0
Reputation: 77850
Your problem is here:
for k in range(0,len(lst)):
if lst[k] < lst[k+1]:
When k=4
( which is len(list) ), then k+1
is out of range. Make your loop statement
for k in range(0,len(lst) - 1):
Upvotes: 2