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.