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']

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay