Python Lab · Experiment 14
Check if a list is sorted using a function
PythonWeek 4JNTUH R22 · CS206ES
Aim
To write a Python function is_sorted that takes a list and returns True if it is sorted in ascending order and False otherwise, and to test it on several lists.
Algorithm
- Define the function is_sorted(items).
- For each position i from 0 to len(items) − 2, compare items[i] with items[i + 1].
- If items[i] is greater than items[i + 1], the list is not in ascending order. Return False.
- If the loop finishes without finding such a pair, return True.
- Call the function on several test lists, including an unsorted list, a list with equal neighbours, an empty list and a list of strings, and print each result.
Program
def is_sorted(items):
"""Return True if items is in ascending order, else False."""
for i in range(len(items) - 1):
if items[i] > items[i + 1]:
return False
return True
test_lists = [
[1, 2, 2, 3, 5],
[1, 3, 2, 4],
[9, 7, 5, 3],
[],
[42],
["apple", "banana", "cherry"],
["b", "a"],
]
for items in test_lists:
print(f"is_sorted({items}) = {is_sorted(items)}")Output
is_sorted([1, 2, 2, 3, 5]) = True
is_sorted([1, 3, 2, 4]) = False
is_sorted([9, 7, 5, 3]) = False
is_sorted([]) = True
is_sorted([42]) = True
is_sorted(['apple', 'banana', 'cherry']) = True
is_sorted(['b', 'a']) = FalseRecorded by running this exact program.
How it works
Each item is compared only with the next one. If every neighbouring pair is in order, the whole list is in order, so one pass is enough.
Equal neighbours are allowed: [1, 2, 2, 3] counts as sorted because the test is >, not >=.
An empty list and a one-item list are sorted. range(len(items) - 1) is then empty, the loop does not run, and the function returns True.
A shorter version is items == sorted(items), but it builds a sorted copy of the whole list, which takes more time and memory than one pass.
Common mistakes
Looping
for i in range(len(items))and readingitems[i + 1]. On the last passi + 1is past the end and Python raisesIndexError. Loop tolen(items) - 1.Returning True inside the loop as soon as one pair is in order. One good pair proves nothing; return True only after the loop.
Using
>=in the test. Then a list with equal values, like[1, 2, 2], is reported as not sorted.Calling
items.sort()inside the function. It changes the caller's list, and it returnsNone, so comparing with it does not work.
Viva questions
Try to answer each one aloud before you open it.
How does the function decide that a list is sorted?
It checks every pair of neighbouring items. If no item is greater than the one after it, the list is in ascending order.
Why does the loop run only up to len(items) - 1?
Each pass compares
items[i]withitems[i + 1]. The last valid i islen(items) - 2, so thati + 1is still a valid index.Does the function work for strings?
Yes. Strings are compared character by character in dictionary (Unicode) order, so
"apple" < "banana"is True.What is the difference between sort() and sorted()?
list.sort()sorts the list in place and returnsNone.sorted(list)leaves the original alone and returns a new sorted list.What is the time complexity of is_sorted?
O(n), because it looks at each neighbouring pair once.