





Please login

Prepinsta Prime
Video courses for company/skill based Preparation

Prepinsta Prime
Purchase mock tests for company/skill building
Difference between Sort() and Sorted() in Python
Sort() vs Sorted() :
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. 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.

Syntax – Sort() :
list_name . sort()
It will arrange the elements in asscending order.
Syntax – Sorted() :
sorted( iterable , key , reverse )
Parameters : sorted takes three parameters from which two are optional.
Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Key(optional) : A function that would server 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.
Note: sort() can only sort list , but sorted() can sort list , tuple or any other sequence type.
Code #1 :
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 :
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'
Sort function can not , sort tuple because sort is defined for list -sequence type only.
Login/Signup to comment