Trusted answers to developer questions

What is the difference between sort() and sorted() in Python?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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)

This method doesn’t change the original list. (Refer Example 1, line 8)

  • Return Type : returns a sorted list. (Refer Example 1, line 7)

  • Iterable: It can be operated on any sequence (list, tuple, string), collection (dictionary, set, frozenset), or other iterator that needs to be sorted. (Refer Example-2)

sort()

Syntax

List_name.sort(key, reverse=False)

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() is a method of the list class, so it can only be used with lists.

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

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

RELATED TAGS

python
Did you find this helpful?