Sorting is the act of rearranging a given sequence.
In Python, sorting is easily done with the built-in methods sort ()
and sorted()
.
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()
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()
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.
# based on alphabetical order of first lettercourts=["Supreme","High","District"]print(" the original list :",courts)# using sorted()new_list=sorted(courts)print("using_sorted():",new_list)#returns a sorted listprint("aft_sorting_lst",courts)#doesn't change original list#using sort()k=courts.sort()print("using_sort():",k)#returns Nothingprint("aft_sort_lst:",courts) #changes the original list
#Using diff datatypes sorting through sorted() methodcourts=["Supreme","High","District"]print(sorted(courts))#listcourts=("Supreme","High","District")#tupleprint(sorted(courts))courts="high"#stringprint(sorted(courts))courts={'Supreme':1,'High':2,'District':3}#dictionaryprint(sorted(courts))courts={"Supreme","High","District"}#setsprint(sorted(courts))#sort() is used only for lists#print("using sort():",courts.sort())# attribute error