Home >Backend Development >Python Tutorial >How Can I Efficiently Check if a Python List is Sorted?

How Can I Efficiently Check if a Python List is Sorted?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 08:55:021028browse

How Can I Efficiently Check if a Python List is Sorted?

Is There a Pythonic Method for Determining List Sorting Status?

In Python, developers often encounter the need to ascertain if a given list is sorted in either ascending or descending order. While there is no native "isSorted()" method, there is a concise and efficient Pythonic approach to achieve this.

To determine the sorting status of a list, such as a chronological list of timestamps, consider the following elegant one-liner:

<code class="python">all(l[i] <= l[i+1] for i in range(len(l) - 1))

This expression evaluates whether all elements in the list are in non-decreasing order (<=), returning True if true and False if false. For ascending order, use <=, while for descending order, use >=.

For example:

list_timestamps = [1, 2, 3, 5, 6, 7]
is_sorted_ascending = all(l[i] <= l[i+1] for i in range(len(l) - 1))

In this case, is_sorted_ascending would evaluate to True as the list is sorted in ascending order.

This Pythonic approach provides a succinct and efficient way to check the sorting status of lists, particularly useful for verifying the chronological order of event sequences or other ordered data structures.

The above is the detailed content of How Can I Efficiently Check if a Python List is Sorted?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn