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.
To run the program, save it as sorting.py
and use python
:
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.