+ 2

Which type of arrangements can I give to sort function in python

I want to sort a list of name by the length of each name and not by alphabet order.

10th Nov 2020, 2:32 PM
Jack Murimi Kavita
Jack Murimi Kavita - avatar
2 Respuestas
+ 8
As Abhay mentioned you can use sort(), that will do the sorting "in-place", so the initial list will be changed. As sort() does not give a return value, it should not be used in combination with print. So 2 steps are needed: sort, print. - There is also an other possible solution by using sorted(). Using this, a new list will be created, the initial list will stay unchanged. - Additionally there is an option for both versions to define whether sorting will be done ascending (default) or descending (using reverse= True) sorted() gives a return value, so it will print correctly. There is only one step needed: sort + print. inp = 'This is Major Tom to ground control'.split(' ') print(sorted(inp, key=len, reverse=True))
10th Nov 2020, 4:55 PM
Lothar
Lothar - avatar
+ 4
sort(key=len)
10th Nov 2020, 2:35 PM
Abhay
Abhay - avatar