YouTip LogoYouTip

Python Sort List

## Python: How to Sort a List Sorting is one of the most fundamental operations in programming. In Python, you can easily sort the elements of a list using either the built-in `list.sort()` method or the global `sorted()` function. This tutorial explains the differences between these two approaches, their syntax, and how to use them effectively with practical examples. --- ## The Two Ways to Sort in Python Python provides two distinct ways to sort a list: 1. **`list.sort()` (In-place sorting):** This is a method of the list class. It modifies the original list directly (in-place) and returns `None`. 2. **`sorted()` (Returns a new list):** This is a built-in global function. It accepts any iterable (including lists) and returns a *new* sorted list, leaving the original list unchanged. --- ## Syntax and Parameters Both `list.sort()` and `sorted()` accept the same two optional keyword-only arguments: ```python # In-place method list.sort(key=None, reverse=False) # Global function sorted(iterable, key=None, reverse=False) ``` ### Parameters: * **`key`** *(optional)*: A function that serves as a key for the sort comparison. For example, `key=len` sorts strings by their length, or `key=str.lower` performs a case-insensitive sort. * **`reverse`** *(optional)*: A boolean value. If set to `True`, the list elements are sorted in descending order. The default is `False` (ascending order). --- ## Code Example Below is a practical example demonstrating how to use both `sort()` and `sorted()`. ```python # Define an unsorted list of numbers numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] # 1. Using the sort() method (In-place sorting) # This directly modifies the original 'numbers' list numbers.sort() print("List sorted using sort() (original modified):", numbers) # Reset the list for demonstration numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] # 2. Using the sorted() function (Returns a new list) # This leaves the original 'numbers' list intact sorted_numbers = sorted(numbers) print("New list returned by sorted():", sorted_numbers) print("Original list remains unchanged: ", numbers) ``` ### Output: ```text List sorted using sort() (original modified): [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] New list returned by sorted(): [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] Original list remains unchanged: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] ``` --- ## Advanced Sorting Examples ### 1. Sorting in Descending Order To sort elements from highest to lowest, pass the `reverse=True` argument. ```python numbers = [3, 1, 4, 1, 5, 9] numbers.sort(reverse=True) print("Sorted in descending order:", numbers) # Output: [9, 5, 4, 3, 1, 1] ``` ### 2. Custom Sorting with the `key` Parameter You can customize the sorting logic by passing a function to the `key` parameter. ```python # Sort strings by their length words = ["banana", "apple", "cherry", "kiwi"] sorted_words = sorted(words, key=len) print("Sorted by length:", sorted_words) # Output: ['kiwi', 'apple', 'banana', 'cherry'] ``` --- ## Key Considerations & Best Practices | Feature | `list.sort()` | `sorted()` | | :--- | :--- | :--- | | **Modification** | Modifies the list in-place. | Creates and returns a new list. | | **Return Value** | Returns `None`. | Returns the sorted list. | | **Memory Usage** | More space-efficient (no copy is made). | Uses more memory because it duplicates the list. | | **Applicability** | Can only be used on `list` objects. | Can be used on any iterable (tuples, dictionaries, sets, etc.). | * **Performance Tip:** If you do not need to keep the original order of the list, use `list.sort()`. It is faster and more memory-efficient because it avoids creating a copy of the data. * **Type Safety:** Python's sorting algorithms require the elements in the list to be comparable. Attempting to sort a list containing incompatible types (e.g., a mix of integers and strings like `[1, 'two', 3]`) will raise a `TypeError`.
← Python Last WordPython List To Dict β†’