Difference between Sort() and Sorted() in Python
Sort() vs Sorted() in Python:
On this page, we will learn the key difference between Sort() vs Sorted() in Python. The main difference between the sort() function and the sorted() function is that the sort function will modify the list it is called on. The sorted() function will create a new sequence type containing a sorted version of the sequence it is given.
Difference between Sort() and Sorted() Function in Python
The sorted() function will not modify the sequence passed as a parameter. If you want to sort a list but still have the original version, then you would use the sorted()
function. If maintaining the original order is unimportant, then you can call the sort() function on the sequence.
Iterable :sequence (list, tuple, string) or collection (dictionary, set, frozen set) or any other iterator that needs to be sorted.
Key(optional) : A function that would serve as a key or a basis of sort comparison.
Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
Code 1 :
# Python Program # Sorted vs sort li = [3, 1, 2, 4] print("using Sorted function :", sorted(li)) print("list remains same :", li) # sorting using sort method li.sort() print("List is changed and sorted :", li)
Output :
using Sorted function: [1, 2, 3, 4]
list remains same : [3, 1, 2, 4]
List is changed and sorted : [1, 2, 3, 4]
Code 2 :
# Python Program # Sorted vs sort li = (3, 1, 2, 4) print("using Sorted function :", sorted(li)) print("Tuple remains same :", li) # sort using sort method li.sort() print("List is changed and sorted :", li)
Output :
using Sorted function: [1, 2, 3, 4]
Tuple remains same : (3, 1, 2, 4)
Traceback (most recent call last):
File “./prog.py”, line 11, in
AttributeError: ‘tuple’ object has no attribute ‘sort’
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment