how to sort a list in python
- User
how to sort a list in python
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
how to sort a list in python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To sort a list in Python, you can use either the sort() method or the sorted() function. Both allow sorting in ascending or descending order and support custom sorting criteria. Here's how they work:
sort() MethodThe sort() method modifies the list in place, meaning it changes the original list and does not return a new one.
list.sort(reverse=False, key=None)
reverse: If True, sorts in descending order. Default is False (ascending order).key: A function that specifies the sorting criteria.numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 9]
numbers = [5, 2, 9, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 5, 2, 1]
words = ["apple", "banana", "kiwi"]
words.sort(key=len)
print(words) # Output: ['kiwi', 'apple', 'banana']
sorted() FunctionThe sorted() function returns a new sorted list without modifying the original list. It works with any iterable (e.g., lists, tuples, dictionaries).
sorted(iterable, reverse=False, key=None)
sort().numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 9]
print(numbers) # Original list remains unchanged
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [9, 5, 2, 1]
words = ["apple", "banana", "kiwi"]
sorted_words = sorted(words, key=len)
print(sorted_words) # Output: ['kiwi', 'apple', 'banana']
sort() and sorted()| Feature | sort() | sorted() |
|---|---|---|
| Modifies Original List | Yes | No |
| Returns New List | No | Yes |
| Works on Iterables | No (only lists) | Yes (any iterable) |
Both methods are versatile and allow for sorting based on custom criteria using the key parameter, making them suitable for a wide range of use cases[1][2][4][5][7].