In Python sort()
vs sorted()
When sorting lists in Python, you can use either the sort()
method or the sorted()
function. Below is a detailed comparison of these two approaches, including code examples, tips, and warnings.
Comparison Table
Feature | sort() Method |
sorted() Function |
---|---|---|
Modifies Original List | Yes | No |
Returns | None (modifies list in place) | New sorted list |
Usage | Only for lists | Works with any iterable |
Syntax | list.sort() |
sorted(iterable) |
Code Examples
Using sort()
The sort()
method sorts a list in place, meaning it modifies the original list and does not return a new list.
# Example list
my_list = [4, 2, 3, 1]
# Using sort()
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
Using sorted()
The sorted()
function returns a new sorted list from the elements of any iterable.
# Example list
my_list = [4, 2, 3, 1]
# Using sorted()
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 3, 4]
# Original list remains unchanged
print(my_list) # Output: [4, 2, 3, 1]
Tips
- Choosing Between
sort()
andsorted()
:- Use
sort()
if you need to sort a list in place and do not need to retain the original order. - Use
sorted()
if you need a sorted version of the iterable but also need to keep the original order intact.
- Use
- Custom Sorting:
- Both
sort()
andsorted()
accept akey
parameter for custom sorting. For example, sorting by the length of strings:my_list = ['apple', 'banana', 'cherry'] my_list.sort(key=len) print(my_list) # Output: ['apple', 'cherry', 'banana']
- Both
Warnings
- Modifying Original List:
- The
sort()
method modifies the original list. If you need to keep the original list unchanged, usesorted()
.
- The
- Performance Considerations:
- For large datasets, consider the overhead of creating a new list with
sorted()
versus modifying the original list withsort()
.
- For large datasets, consider the overhead of creating a new list with
Leave a Reply