list.sort() and sorted() functions in Python
In Python, you can sort a list or array in two ways. The first is a built-in function sorted()
and the second is a list method list.sort()
.
Using the sorted()
function
The sorted()
function takes a list as argument and returns a sorted list. The original list is unchanged.
Let us demonstrate it with an example. We will sort a list of numbers and create a new list with the numbers sorted.
numbers = [4, 6, 8, 2, 3]
print(numbers)
s_numbers = sorted(numbers)
print(s_numbers)
Output:
[4, 6, 8, 2, 3] [2, 3, 4, 6, 8]
Points to note:
- List
numbers
was not changed during the sorting sorted()
returnd the sorteed list, which was then assigned tos_numbers
Using the list.sort() method
The .sort()
method is a built-in method of the list object. In this case, the list is updated with the sorted list. It also returns null.
Let us demonstrate it with an example. We will sort a list of numbers and update the list in-place with the sorted numbers.
numbers = [4, 6, 8, 2, 3]
print(numbers)
numbers.sort()
print(numbers)
Output:
[4, 6, 8, 2, 3] [2, 3, 4, 6, 8]
Points to note:
- List
numbers
was changed during the sorting numbers.sort()
did not return anything, but updated itself with the sorted numbers
When to use sorted()
vs list.sort()
When you want to sort an existing list and update that same list, then use list.sort()
.
When you want to retain the original unsorted list and keep a sorted version of the same list, use the sorted()
function.
Performance: list.sort() vs sorted(list)
In terms of space complexity, sort()
is more memory efficient. This is because it sorts in-place, so you do not require extra memory space to store the new sorted list, which is what sorted()
does. sort()
is faster than sorted()
because it sorts the list in-place.
Comparison Table list.sort() vs sorted(list)
sort() | sorted() | |
---|---|---|
In-place sorting | Yes | No |
Data preservation | Does not preserve the original data | Preserves the original data |
Custom sorting criteria | Yes | Yes |
Which is more efficient? | sort() has better performance | sorted() requires more space |
What does it return? | null | sorted list |
Works with | only lists | with all iterables, including lists, tuples, strings and dictionaries |
What type of function? | method for list object | built-in function that takes list as argument |
Conclusion
If you found this blog post useful, feel free to share it. Thanks for reading.
Related Posts
If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.