You can sort the list using the sort() or sorted() Python function. You must be thinking about then what is the difference between sort() and sorted() function.
The main difference between the list
sorted() Python function is that the
sort() the function will modify the list it is called on. The sorted() function will create a new list containing a sorted version of the list it is given.
Let’s see How both used and their syntax:-
list.sortmutates the list in place & returns
sortedtakes any iterable & returns a new list, sorted.
Example between sort vs sorted Python Function
sorted(iterable, key=key, reverse=reverse)
number_list = [1, 3, 2, 4] print(sorted(number_list))
Output: [1, 2, 3, 4]
numbers = [5, 3, 4, 2, 1] # Sorting list of Integers in ascending numbers.sort() print(numbers)
Output: [1, 2, 3, 4, 5]
All common sort vs sorted python Questions
Here are some common doubt between sort() vs sorted() function in python:-
1. When is one preferred over the other?
list.sort() when you want to mutate the list
sorted() when you want a new sorted object back. Use
sorted() when you want to sort something that is an iterable object, not a list yet.
2. Which is more efficient? By how much?
Answer: For lists,
list.sort() is faster than
sorted() because it doesn’t have to create a copy. For any other iterable object, you have no choice.
3. Can a list be reverted to the unsorted state after
list.sort() has been performed?
Answer: No, you cannot retrieve the original positions. Once you called
list.sort() the original order is gone.
Do comment if you know any other differences and doubts about this tutorial.
IDE: PyCharm 2020.1.1 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.