How do I sort lists in Python with standard library only?

In Python, you can sort lists using the built-in sort() method or the sorted() function. Both methods sort lists in ascending order by default, but you can also specify a custom sorting order.

Using the sort() Method

The sort() method sorts the list in place, meaning that it modifies the original list.

# Example of using sort() my_list = [5, 2, 9, 1, 5, 6] my_list.sort() print(my_list) # Output: [1, 2, 5, 5, 6, 9]

Using the sorted() Function

The sorted() function returns a new sorted list from the elements of any iterable.

# Example of using sorted() my_list = [5, 2, 9, 1, 5, 6] sorted_list = sorted(my_list) print(sorted_list) # Output: [1, 2, 5, 5, 6, 9]

Sorting in Descending Order

You can sort lists in descending order by setting the reverse parameter to True.

# Example of sorting in descending order my_list = [5, 2, 9, 1, 5, 6] my_list.sort(reverse=True) print(my_list) # Output: [9, 6, 5, 5, 2, 1]

python sort lists sort method sorted function descending order