7.9. Sort a list#

7.9.1. You can use .sort() or sorted() methods#

list.Sort()

sorted(list)

Difference: sorts the list in-place and change the original list & returns None

takes a list,(or any iterable) ,sort it & returns a new list,sorted

Works only on lists

Works with any iterable(str,list,dict,tupple)

Syntax: list.sort([key=…], [reverse=True/False)]

new_list=sorted(list, [key=…], [reverse=True/False)]

Explanation: Since in place so no need to store anywhere and use .

Since creates a new list so we need to store it somewhere and org one is passed as args

7.9.2. Example of using sort()#

a = [3, 2, 1]
print (a.sort()) # in place
print (a)        # it's modified
None
[1, 2, 3]

7.9.3. Example of using sorted()#

a = [3, 2, 1]
print (sorted(a))  # new list,you will need to store it somewhere
print (a)         # is not modified
[1, 2, 3]
[3, 2, 1]

7.9.4. Keys#

names=['Sahil','Sonia','Abhi','Sourav']
age=[10,20,30]
names.sort()
print(names)
['Abhi', 'Sahil', 'Sonia', 'Sourav']

7.9.5. What if repeated letters?#

l=['A','B','C','D','A','AA']
l.sort()
l
['A', 'A', 'AA', 'B', 'C', 'D']