Jun-18-2019, 01:33 AM
The OP's solution is superior to the one-liner in two ways:
The big-O of the OP's solution is O(n), whereas the version using sorted() is O(n**2) (or whatever Tim-sort is; definitely not linear)
The OP's code can return immediately upon finding that the list isn't sorted, it doesn't even have to do n work.
As others have mentioned enumerate(), I tend to use it instead of range(len()) just to communicate to the reader that I really do need the index. That said, I would use itertools' islice (and izip if Python 2) and avoid indexes entirely, the only time I find myself actually needing indexes is for some interview questions.
The big-O of the OP's solution is O(n), whereas the version using sorted() is O(n**2) (or whatever Tim-sort is; definitely not linear)
The OP's code can return immediately upon finding that the list isn't sorted, it doesn't even have to do n work.
As others have mentioned enumerate(), I tend to use it instead of range(len()) just to communicate to the reader that I really do need the index. That said, I would use itertools' islice (and izip if Python 2) and avoid indexes entirely, the only time I find myself actually needing indexes is for some interview questions.