idkman
idkman

Reputation: 169

What is the Pythonic way to check if a list of strings is sorted or not?

I have a list of strings

my_string_list = ['Banana', 'Apple', 'Sorry']

How can I check if this my_string_list is sorted or not?

One obvious way is to sort this list and compare it against the original list. But I do not want to iterate over the whole original list to decide that the list is not sorted.

sorted_list_of_strings = sorted(my_string_list)
if my_string_list != sorted_list_of_strings:
    print(f'The list {my_string_list} is not sorted.')

I am wondering if there is any other way to do this?

Upvotes: 0

Views: 538

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155506

Typically, I'd use your solution (if x == sorted(x):) and accept the cost; it's easy to write, and if it's not a hot code path, it hardly matters if you're doing it somewhat inefficiently (for the already-sorted case, it'll be roughly O(n) anyway thanks to Python's TimSort, so you only pay O(n log n) general sort costs for the "not sorted" case). It's also easy to customize when you need to handle reverse sorting, keyed sorting, etc., while remaining easy to write and easy to verify by inspection.

If you want a more efficient solution using Python builtins, you could do something along the lines of (with from operator import le at the top of the file):

if all(map(le, my_string_list, my_string_list[1:])):

which compares each element to the following element, returning False on the first mismatch, and True if they're all less than or equal to the following element. Replace my_string_list[1:] with itertools.islice(my_string_list, 1, None) if you have concerns about the cost (computational or memory cost) of building the temporary list with the plain slice.

Upvotes: 3

Related Questions