Sometimes, we want to check if a list is sorted or not with Python.
In this article, we’ll look at how to check if a list is sorted or not with Python.
How to check if a list is sorted or not with Python?
To check if a list is sorted or not with Python, we can use the all
function.
For instance, we write
is_sorted = all(l[i] <= l[i+1] for i in range(len(l) - 1))
to call all
to check if every item in list l
is sorted.
We use range
to return an iterator with the index of l
from 0 to len(l) - 2
.
And check if the next item is bigger than the current one with
l[i] <= l[i+1]
Conclusion
To check if a list is sorted or not with Python, we can use the all
function.