DEV Community

sravya206888
sravya206888

Posted on

Difference between sort() and sorted() in Python

Sorting is the act of rearranging a given sequence. In Python, sorting is easily done with the built-in methods sort () and sorted().
. The sorted() and sort() methods sort the given sequence in either ascending or descending order.
Though these two methods perform the same task, they are quite different.
-> sorted():
Syntax:

sorted(iterable, key, reverse=False)
Enter fullscreen mode Exit fullscreen mode

This method makes changes to the original sequence.(Refer example-1,line-13)

Return Type: returns none, has no return value.(Refer Example-1,line-12)

->sort():
sort() function is very similar to sorted() but it returns nothing and makes changes to the original sequence which differs it from sorted function.
sort() is a method of the list class, so it can only be used with lists.
Syntax:

List_name.sort(key, reverse=False)
Enter fullscreen mode Exit fullscreen mode

Example-1:

# based on alphabetical order of first letter
courts=["Supreme","High","District"]
print(" the original list :",courts)

# using sorted()
new_list=sorted(courts)
print("using_sorted():",new_list)#returns a sorted list
print("aft_sorting_lst",courts)#doesn't change original list

#using sort()
k=courts.sort()
print("using_sort():",k)#returns Nothing
print("aft_sort_lst:",courts) #changes the original list
Enter fullscreen mode Exit fullscreen mode

output:

the original list : ['Supreme', 'High', 'District']
using_sorted(): ['District', 'High', 'Supreme']
aft_sorting_lst ['Supreme', 'High', 'District']
using_sort(): None
aft_sort_lst: ['District', 'High', 'Supreme']
Example-2:

#Using diff datatypes sorting through sorted() method

courts=["Supreme","High","District"]
print(sorted(courts))#list
courts=("Supreme","High","District")#tuple
print(sorted(courts))
courts="high"#string
print(sorted(courts))
courts={'Supreme':1,'High':2,'District':3}#dictionary
print(sorted(courts))
courts={"Supreme","High","District"}#sets
print(sorted(courts))

#sort() is used only for lists
#print("using sort():",courts.sort())
#  attribute error
Enter fullscreen mode Exit fullscreen mode

output:
['District', 'High', 'Supreme']
['District', 'High', 'Supreme']
['g', 'h', 'h', 'i']
['District', 'High', 'Supreme']
['District', 'High', 'Supreme']

Discussion (0)