Sorting in Python

Our example demonstrates sorting for built-in types in Python. We’ll use the built-in sorted() function and the sort() method for lists.

# Sorting functions work for any comparable built-in type.

# Sorting strings
strs = ["c", "a", "b"]
sorted_strs = sorted(strs)
print("Strings:", sorted_strs)

# An example of sorting integers
ints = [7, 2, 4]
ints.sort()
print("Ints:   ", ints)

# We can also check if a list is already in sorted order
s = sorted(ints) == ints
print("Sorted: ", s)

To run the program, save it as sorting.py and use python:

$ python sorting.py
Strings: ['a', 'b', 'c']
Ints:    [2, 4, 7]
Sorted:  True

In Python, the sorted() function returns a new sorted list from the given iterable, while the sort() method sorts the list in-place. The sorted() function can be used on any iterable, not just lists.

For checking if a list is sorted, we compare the original list with a sorted version of itself. This approach works but may not be the most efficient for large lists. For a more efficient method, you could implement a function that checks adjacent elements.

Python’s sorting is stable, meaning that when multiple records have the same key, their relative order is preserved in the sorted result.

For more advanced sorting scenarios, such as sorting by custom functions or multiple criteria, you can use the key parameter of sorted() and sort(), or the functools.cmp_to_key() function for complex comparisons.