sort and sorted
时间: 2023-11-11 17:17:57 浏览: 114
"sort" and "sorted" are both related to sorting elements in a list or sequence.
- "sort" is a method that can be applied directly to a list to sort its elements in ascending order. It modifies the original list in-place.
- "sorted" is a built-in function that takes an iterable (e.g., a list, tuple, or string) as an argument and returns a new sorted list without modifying the original input.
Here's an example to illustrate the difference:
```python
numbers = [4, 2, 1, 3]
# Using sort()
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
# Using sorted()
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4]
print(numbers) # Output: [4, 2, 1, 3] (original list remains unchanged)
```
In summary, "sort" sorts the list in-place, while "sorted" returns a new sorted list without modifying the original.
阅读全文