Artificial Intelligence
Please fill the required field.

Python list sort


In Python, you can sort a list using the `sort()` method or the `sorted()` function. Here's a brief overview of both methods: ### Using `sort()` The `sort()` method sorts the list in place (i.e., it modifies the original list) and does not return a new list. It sorts the list in ascending order by default. ```python # Example of using sort() numbers = [5, 2, 9, 1, 5, 6] numbers.sort() print(numbers) # Output: [1, 2, 5, 5, 6, 9] ``` You can also sort in descending order by passing the `reverse=True` argument: ```python # Example of sorting in descending order numbers.sort(reverse=True) print(numbers) # Output: [9, 6, 5, 5, 2, 1] ``` You can also use a custom sorting key by passing a function to the `key` parameter: ```python # Example of sorting using a custom key words = ['banana', 'apple', 'cherry'] words.sort(key=len) # Sorts by length of words print(words) # Output: ['apple', 'banan', 'cherry'] ``` ### Using `sorted()` The `sorted()` function returns a new sorted list from the elements of any iterable (e.g., list, tuple, string) and does not modify the original iterable. ```python # Example of using sorted() numbers = [5, 2, 9, 1, 5, 6] sorted_numbers = sorted(numbers) print(sorted_numbers) # Output: [1, 2, 5, 5, 6, 9] print(numbers) # Original list remains unchanged ``` Like `sort()`, you can also sort in descending order, and you can use the `key` parameter: ```python # Example of sorting using sorted() in descending order sorted_numbers_desc = sorted(numbers, reverse=True) print(sorted_numbers_desc) # Output: [9, 6, 5, 5, 2, 1] # Sort by length using sorted() words = ['banana', 'apple', 'cherry'] sorted_words = sorted(words, key=len) print(sorted_words) # Output: ['apple', 'banana', 'cherry'] ``` ### Summary - Use `.sort()` when you want to sort a list in place. - Use `sorted()` when you want to create a new sorted list from any iterable.