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. 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.

Sort() vs Sorted() in Python

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.

sort vs sorted in python

Code #1 :

Run
# 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 :

Run
# 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'