Planet Python

Real Python: How to Use sorted() and .sort() in Python

Sorting in Python can be done using the `sorted()` function and the `.sort()` method. The `sorted()` function returns a new sorted list from any iterable without modifying the original, while the `.sort()` method sorts a list in place and doesn't return a value. Both methods support customization through optional keyword arguments like `key` and `reverse`. The `sorted()` function can be used to sort any iterable, and it returns a new sorted list. The `.sort()` method sorts the list in place and doesn't return a value. To sort items in descending order, set the `reverse` argument to `True`. The `key` argument accepts a function to customize the sort order. The `sorted()` function can be used on lists, tuples, and sets, and it returns a new list by definition. The returned object can be cast to a new type if it needs to match the input type, but be careful when casting to a set as it is unordered.
favicon
realpython.com
realpython.com
Image for the article: Real Python: How to Use sorted() and .sort() in Python
Create attached notes ...