## petew71 2 years ago Checking a list to see if it's sorted. I'm trying to write a function that takes a list and checks to see if its sorted in ascending order. At the moment i can only manage it by copying the list, sorting the copy, and comparing the two. But, it's not in the spirit of the exercise. I should really be using iteration and comparison operators! Can anyone assist?

1. slotema

The basic approach would be to get the current element and the next element and check whether or not they're stored in correct order. You'll need to do this for each element in the list.

2. petew71

Well, i got to this (below). But, It looks kinda messy, and it doesn't work with letters! def is_sorted(l): """ checks to see if a list is in ascending order""" for look in range(0,len(l)): if [look] > l[look]+1 or l[-2] > l[-1]: return False return True print is_sorted([1,3,5,7,6])

3. slotema

The problem seems to be in your comparison: `if [look] > l[look]+1 or l[-2] > l[-1]:`. There are two main problems. First, though this could be a typo, you compare `[look]`, which is a list with `l[look]+1`, which is a number. You should really compare `l[look]` instead of `[look]`. Second, there's the `l[look]+1`. What this says is basically: give me the value of `l[look]` and add one to it. This way, `l[look]` will always be smaller than `l[look]+1`. What you'd want instead is the value of `l` at index `loop+1`.

4. petew71

Ahh, yes..It was a typo. Or to be more accurate, a copy-and-pasteo (which was playing up!) sorry...! As to your second point..I have made a modification thanks to your hint. I've also done a different version of the function. Which do you think is a better example of code practice? I have tested both and can find no errors. Many thanks for your input ! def is_sorted(t): """ checks to see if a list is in ascending order""" for look in range(0,len(t)-1): if t[look] > t[look+1] or t[-2] > t[-1]: return False return True print is_sorted([1,3,5,8,7]) print is_sorted(['c','e','g']) def another_is_sorted(t): """ checks to see if a list is in ascending order""" for look in range(0,len(t)-1): first_item, next_item = t[look], t[look+1] if first_item > next_item: return False return True print another_is_sorted([2,4,6,]) print another_is_sorted(['a','b','d','c'])

5. slotema

I don't really know which one is better code practice. Apart from the or part in the first function (which you don't really need anymore, I think), if you use t[look] and t[look+1] more often, I'd say the second function would be better. Another thing, in you use range and want it started at 0, you can just say e.g. range(len(t)-1). Range'll know that you want to start from 0.

6. petew71

Thanks for those pointers...and taking time out to help!

7. slotema

No problem :)