How to Sort A List in Python

Use sort() for In-Place Sorting

The sort() method sorts a list in ascending order by default and modifies the original list: my_list.sort().

Use sorted() for a New List

sorted() returns a new sorted list without changing the original: sorted_list = sorted(my_list).

Sort in Descending Order

Add reverse=True to sort() or sorted(): my_list.sort(reverse=True) or sorted(my_list, reverse=True).

Sort by Key

Use the key parameter to define custom sorting logic. Example: my_list.sort(key=len) sorts by string length.

Sort Complex Lists

For lists of tuples/dictionaries, use key to sort by specific elements: sorted(data, key=lambda x: x[1]) for tuple second elements.

Preserve Original List Order

Prefer sorted() if you need to retain the original list order while creating a sorted copy.